73

我的一些代码:

            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

pep8 警告是:

trailing whitespace 37:try
trailing whitespace 43:pass

你能告诉我这是什么吗?

4

4 回答 4

48

尾随空格是行上最后一个非空白字符之后直到换行符的任何空格或制表符。

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

>>> 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            '

看看字符串在哪里结束?行前有空格(缩进),但也有空格。

使用编辑器查找行尾和退格键。许多现代文本编辑器还可以自动删除行尾的尾随空格,例如每次保存文件时。

于 2014-01-28T15:40:49.440 回答
29

尾随空格:

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

于 2015-06-08T06:13:56.723 回答
10

这只是一个警告,它不会对您的项目运行造成问题,您可以忽略它并继续编码。但是如果你和我一样痴迷于干净的编码,你有两个选择:

  1. 将鼠标悬停在 VS Code 或任何 IDE 中的警告上,并使用快速修复来删除空格。
  2. f1然后键入trim trailing whitespace
于 2020-02-12T13:16:15.930 回答
4

我有类似的 pep8 警告W291 trailing whitespace

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

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

于 2018-03-28T06:31:40.587 回答