Idiomatic portable way to strip line endings?

Tim Hammerquist tim at
Sun Dec 16 11:22:43 EST 2001

Ulf Magnusson <ulf.magnusson at> graced us by uttering:
>> In general, I can use:
>>     line = line[:-1]
>> or
>>     del line[-1:]
> There is an easy way to print them without the newline
> print "hello world",
> Use a comma attached at the end, this ofcourse doesn't modify the
> string (strings are unmutable) but it fixes the print output.

I think you misunderstood my question.


    s = "a string\n"

I want:

    s == "a string"

OTOH, when I write filters, yours is the exact idiom I use.

> the string module also supports the following
> rstrip, strip, lstrip
> which removes whitespaces (on the right side, the whole string, left side)

This breaks on strings like:

Start:      " string bookended by whitespace \n"
Target:     " string bookended by whitespace "

w/ .rstrip: " string bookended by whitespace"
w/ .strip:  "string bookended by whitespace"

Often the (l|r)?strip methods work fine, but sometimes I need to
preserve " " and "\t" in the string.

Thanks for you help, tho.  =)

Tim Hammerquist
Microsoft's biggest and most dangerous  contribution to the software
industry may be the degree to which it has lowered user expectations.

More information about the Python-list mailing list