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

2024-04-18 14:58:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的一些代码:

            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

你能告诉我这是什么吗?


Tags: 代码selftitlecountpasscurrentfindquestions
3条回答

尾随空白:

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

我收到了类似的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结尾处有两个空格

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

在您发布的问题中,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            '

看到弦的末端了吗?行之前有空格(缩进),后面也有空格。

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

相关问题 更多 >