python – what is trailing whitespace and how can I handle this?

python – what is trailing whitespace and how can I handle this?

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            
...    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))

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.

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: <file>

import sys

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

content = 
outsize = 0
inp = outp = sys.argv[1]
with open(inp, rb) as infile:
  content =
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))

python – what is trailing whitespace and how can I handle this?

This is just a warning and it doesnt make problem for your project to run, you can just ignore it and continue coding.
But if youre 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.

Leave a Reply

Your email address will not be published. Required fields are marked *