什么是尾随空格,我该如何处理?

84

我有一些像这样的代码:

        if self.tagname and self.tagname2 in list1:
            try: 
                question = soup.find("div", "post-text")
                title = soup.find("a", "question-hyperlink")
                self.list2.append(str(title)+str(question)+url)
                current += 1
            except AttributeError:
                pass            
        logging.info("%s questions passed, %s questions \
            collected" % (count, current))
        count += 1
    return self.list2

我的IDE给了我一些Pep8警告,就像这样:

trailing whitespace 37:try
trailing whitespace 43:pass

这是什么意思,我该如何修复它?


1
这里提供了关于这些警告的良好解释:https://www.flake8rules.com/ 以及你的 https://www.flake8rules.com/rules/W291.html (flake8是一种检查工具) - Sławomir Lenart
空格不会影响您的编码功能,但删除它们肯定会使您的代码更清洁,并避免不必要的小错误。如果您使用VS Code,可以将以下内容放入您的settings.json文件中,以便在保存文件时自动修剪所有空格。"files.trimTrailingWhitespace": true - Hai Tran
我不明白为什么会有这样的问题。它似乎是一个关于英语而不是编程的问题。 "尾随空格" 简单地说就是代码行末尾跟随(trail)的空格 - Karl Knechtel
4个回答

55

未被删除的空格或制表符是指在换行符之前,最后一个非空白字符后面的任何空格或制表符。

在您发布的问题中,try: 后面有一个额外的空格,在 pass 后面有12个额外的空格。

>>> post_text = '''\
...             if self.tagname and self.tagname2 in list1:
...                 try: 
...                     question = soup.find("div", "post-text")
...                     title = soup.find("a", "question-hyperlink")
...                     self.list2.append(str(title)+str(question)+url)
...                     current += 1
...                 except AttributeError:
...                     pass            
...             logging.info("%s questions passed, %s questions \
...                 collected" % (count, current))
...             count += 1
...         return self.list2
... '''
>>> for line in post_text.splitlines():
...     if line.rstrip() != line:
...         print(repr(line))
... 
'                try: '
'                    pass            '

看到字符串的结尾了吗?有行前的空格(缩进),还有行后的空格。

使用您的编辑器找到行尾并退格。许多现代文本编辑器也可以自动删除行末的尾随空格,例如每次保存文件时。


在emacs中:C-M-% <space> + $ 然后按两次回车。哇,当我打字时它看起来比实际感觉更加神秘。 - nmichaels
每行末尾的空格是否有效(并由PEP8报告),而不仅仅是在“:”之后? - Christoph
@Christoph:抱歉,是的,所有尾随空格;那是一个编辑错误。 - Martijn Pieters

31

尾随空格:

It is extra spaces (and tabs) at the end of line      
                                                 ^^^^^ here

去除它们:

#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""

import sys

if len(sys.argv[1:]) != 1:
  sys.exit(__doc__)

content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
  content = infile.read()
with open(outp, 'wb') as output:
  for line in content.splitlines():
    newline = line.rstrip(" \t")
    outsize += len(newline) + 1
    output.write(newline + '\n')

print("Done. Stripped %s bytes." % (len(content)-outsize))

https://gist.github.com/techtonik/c86f0ea6a86ed3f38893


14

这只是一个警告信息,不会影响您的项目运行,您可以忽略它并继续编码。但如果您像我一样追求代码整洁,有两个选项:

  1. 将鼠标悬停在VS Code或任何IDE上的警告上,并使用快速修复功能去除空格。
  2. 按下f1,然后输入trim trailing whitespace

8

我遇到了类似的Pep8警告:W291 尾随空格

long_text = '''Lorem Ipsum is simply dummy text  <-remove whitespace
of the printing and typesetting industry.'''

尝试探索末尾的空格并删除它们。例如: 在Lorem Ipsum is simply dummy text的末尾有两个空格。


对我来说没问题!我只是把 """ 改成了 ''' - natielle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接