Problem loading a file of words

Peter Hansen peter at engcorp.com
Mon Jul 25 17:03:45 CEST 2005


teoryn wrote:
> I changed to using line = line.strip() instead of line = line [:-1] in
> the original and it it worked.

Just to be clear, these don't do nearly the same thing in general, 
though in your specific case they might appear similar.

The line[:-1] idiom says 'return a string which is a copy of the 
original but with the last character, if any, removed, regardless of 
what character it is'.

The line.strip() idiom says 'return a string with all whitespace 
characters removed from the end *and* start of the string'.

In certain cases, you might reasonably prefer .rstrip() (which removes 
only from the right-hand side, or end), or even something like 
.rstrip('\n') which would remove only newlines from the end.

-Peter



More information about the Python-list mailing list