[Tutor] question about strip() and list comprehension
Jared Nielsen
nielsen.jared at gmail.com
Wed Apr 9 00:09:15 CEST 2014
Thank Danny,
That's much more clear.
But I still don't understand what's happening with:
if line.strip()
Is that stripping the line of white space at the same time that it is
testing it?
On Tue, Apr 8, 2014 at 3:44 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
> > 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)
>
>
> Hi Jared,
>
>
> Let me rewrite this without the list comprehension, while preserving
> behavior.
>
> ######################
> inputFile = open('file.txt')
> lines = []
> for line in inputFile.readlines():
> if line.strip():
> lines.append(line)
> inputFile.close()
> print "".join(lines)
> ######################
>
> I am changing the names of the variables from the original code
> because I find it very difficult to distinguish 't' from 'f'
> sometimes, and because those names are very tied in my mind to
> something else entirely ("true" and "false").
>
>
> Does the above code make more sense to you than the version using the
> list comprehension syntax, or is there something there that is still
> confusing?
>
>
> Good luck to you.
>
--
http://jarednielsen.com<http://bl-1.com/click/load/UWUANFE1UWRXMQRlAzI-b0231>
http://thehelloworldprogram.com<http://bl-1.com/click/load/UWUIPFczV2IDZVU0CDY-b0231>
http://dototot.com <http://bl-1.com/click/load/ATUBNQNnBjNWMFAxUm0-b0231>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140408/6728d60c/attachment.html>
More information about the Tutor
mailing list