[Tutor] question about strip() and list comprehension
Jared Nielsen
nielsen.jared at gmail.com
Wed Apr 9 04:06:50 CEST 2014
Thanks Danny!
That was an awesome explanation.
On Tue, Apr 8, 2014 at 7:05 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
>
>> if line.strip()
>>
>> Is that stripping the line of white space at the same time that it is
>> testing it?
>>
>>
>
> Two features about Python:
>
> 1. Strings are immutable, so the above is computing what a
> whitespace-stripped line would look like. So that means that
> 'line.strip()' is doing just a computation: it's not mutating the original
> line, but computing a new string that has its leading and trailing
> whitespace stripped away.
>
>
> 2. Empty strings are treated as false values. I'm not happy with how
> loose Python treats truth, and would rather prefer:
>
> if line.strip() != "": ...
>
> so that the thing being tested is explicitly either True or False. I like
> my truth to be black and white, but I suppose I'll have to grimace and bear
> the fuzziness. :P
>
>
> Together, we see those two features allow us to look at the test in the
> Python code:
>
> if line.strip(): ...
>
> and rephrase it in English as:
>
> "If the line consists of at least one non-whitespace character: ..."
>
--
http://jarednielsen.com
http://thehelloworldprogram.com
http://dototot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140408/f38ef817/attachment.html>
More information about the Tutor
mailing list