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.
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to