[Tutor] question about strip() and list comprehension
dyoo at hashcollision.org
Wed Apr 9 03:05:34 CEST 2014
> 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
if line.strip(): ...
and rephrase it in English as:
"If the line consists of at least one non-whitespace character: ..."
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor