NEWBIE: Tokenize command output
Tim Chase
python.list at tim.thechases.com
Fri May 12 09:09:31 EDT 2006
>>starLines = [line for line in p.readlines() if line.startswith("*")]
>
> files are iterators, so no need to use readlines() (unless it's an old
> Python version of course):
>
> starLines = [line for line in p if line.startswith("*")]
Having started with some old Python, it's one of those
things I "know", but my coding fingers haven't yet put into
regular practice. :)
>>or you may optionally want to prune of the "\n" characters in the process:
>>
>>starLines = [line[:-1] for line in p.readlines() if line.startswith("*")]
>
> *please* use str.rstrip() for this:
> starLines = [line.rstrip() for line in p if line.startswith("*")]
They can yield different things, no?
>>> s = "abc \n"
>>> s[:-1]
'abc '
>>> s.rstrip()
'abc'
>>> s.[:-1] == s.rstrip()
False
If trailing space matters, you don't want to throw it away
with rstrip().
Otherwise, just to be informed, what advantage does rstrip()
have over [:-1] (if the two cases are considered
uneventfully the same)?
Thanks,
-tkc
More information about the Python-list
mailing list