[Tutor] question about strip() and list comprehension

Jared Nielsen nielsen.jared at gmail.com
Tue Apr 8 22:38:13 CEST 2014


Hello,
Could someone explain why and how this list comprehension with strip()
works?

f = open('file.txt')
t = [t for t in f.readlines() if t.strip()]
f.close()
print "".join(t)

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, but no clear
explanation as to why it works. I'm particularly confused by how "if
t.strip()" is removing the blank lines. I also don't fully understand the
'print "".join(t)'.

The above didn't remove the leading white space on several lines, so I made
the following addition:

f = open('file.txt')
t = [t for t in f.readlines() if t.strip()]
f.close()
s = [x.lstrip() for x in t]
print "".join(s)

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

Many thanks,
J.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140408/352702c0/attachment.html>


More information about the Tutor mailing list