[Tutor] question about strip() and list comprehension

Ben Finney ben+python at benfinney.id.au
Wed Apr 9 00:30:09 CEST 2014

Jared Nielsen <nielsen.jared at gmail.com> writes:

> I had a very long file of strings filled with blank lines I wanted to
> remove. I did some Googling and found the above code snippet

The code you found is one of several syntactic shortcuts in Python,
which allow creating a sequence directly from an expression in your

For explanations, look at the documentation for “generator expression”
and “display” (the latter have syntax for list comprehension, set
comprehension, and dict comprehension).


> I'm particularly confused by how "if t.strip()" is removing the blank
> lines.

The ‘str.strip’ method returns a new string, constructed from the
original by removing all leading and trailing whitespace

A string, like any object, can be used in a boolean context; that's why
“if some_expression” works for any expression

For an expression that returns a string, the value in a boolean context
will be false if the string is empty, and true for any other string.

So, in the list comprehension you found: the “if t.strip()” is getting a
new string, testing it in a boolean context which will be false when the
string is empty, and that condition is what determines which values will
end up in the sequence.

> I also don't fully understand the 'print "".join(t)'.

Each text string object has a ‘join’ method, which uses that string and
the specified sequence to construct a new string, joining all the items
together <URL:https://docs.python.org/3/library/stdtypes.html#str.join>.

> The above didn't remove the leading white space on several lines

Right. The new “stripped” string is not used except in the “if” clause,
to determine which values will end up in the new list. The original values
themselves are unchanged by the process, and end up in the new list as
they began.

> List comprehensions are still magic to me. How would I go about
> incorporating lstrip() in the first list comprehension?

In general, if something is a mystery to you, look up the formal
description of the method or syntax in the documentation and carefully
follow what it's telling you.

Have a careful read of the documentation for those concepts, experiment
based on your reading, and see what questions you have after that.

 \         “Smoking cures weight problems. Eventually.” —Steven Wright |
  `\                                                                   |
_o__)                                                                  |
Ben Finney

More information about the Tutor mailing list