<div dir="ltr"><div>Hello,<br></div><div>Could someone explain why and how this list comprehension with strip() works?<br><br>f = open('file.txt')<br>t = [t for t in f.readlines() if t.strip()]<br>f.close()<br>print "".join(t)<br>

<br></div><div>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)'.<br>
<br></div><div>The above didn't remove the leading white space on several lines, so I made the following addition:<br><br>f = open('file.txt')<br>t = [t for t in f.readlines() if t.strip()]<br>f.close()<br>s = [x.lstrip() for x in t]<br>

</div><div>print "".join(s)<br><br></div><div>List comprehensions are still magic to me. How would I go about incorporating lstrip() in the first list comprehension?<br><br></div>Many thanks,<br>J.<br clear="all">
<br><br><br><br>
</div>