what is trailing whitespace and how can I handle this?
Asked Answered
L

4

87

I have some code like:

        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

My IDE gave me some pep8 warnings, like so:

trailing whitespace 37:try
trailing whitespace 43:pass

What does this mean, and how do I fix it?

Linea answered 28/1, 2014 at 15:39 Comment(3)
A good explanation of these warnings is given here: flake8rules.com and yours flake8rules.com/rules/W291.html (flake8 is an inspection tool)Scissure
White spaces do not affect your coding function, but removing them definitely makes your code much cleaner and avoids unwanted small mistakes. If you use VS Code, you can put this into your settings.json file to automatically trim all the white spaces whenever you save a file. ``` "files.trimTrailingWhitespace": true ```Fumed
I don't understand how the question could be asked. It seems to be a question about English, not a question about programming. "Trailing whitespace" is simply whitespace which follows (trails) the line of code.Illustrator
W
56

Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.

In your posted question, there is one extra space after try:, and there are 12 extra spaces after 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            '

See where the strings end? There are spaces before the lines (indentation), but also spaces after.

Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.

Whom answered 28/1, 2014 at 15:40 Comment(3)
In emacs: C-M-% <space> + $ then press return twice. Wow, that looks more cryptic than it feels when I type it.Afghani
surely trailing whitespace is valid (and reported by PEP8) on every line, not only after :, right?Telemann
@Christoph: sorry, yes, all trailing whitespace; that was an editing error.Whom
B
31

Trailing whitespace:

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

Strip them:

#!/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

Blackmon answered 8/6, 2015 at 6:13 Comment(0)
I
15

This is just a warning and it doesn't make problem for your project to run, you can just ignore it and continue coding. But if you're obsessed about clean coding, same as me, you have two options:

  1. Hover the mouse on warning in VS Code or any IDE and use quick fix to remove white spaces.
  2. Press f1 then type trim trailing whitespace.
Infield answered 12/2, 2020 at 13:16 Comment(0)
P
8

I have got similar pep8 warning W291 trailing whitespace

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

Try to explore trailing whitespaces and remove them. ex: two whitespaces at the end of Lorem Ipsum is simply dummy text

Prehensile answered 28/3, 2018 at 6:31 Comment(1)
Works to me! I just change """ to '''Soupspoon

© 2022 - 2024 — McMap. All rights reserved.