Idiomatic portable way to strip line endings? (fwd)

Lulu of the Lotus-Eaters mertz at gnosis.cx
Sun Dec 16 21:37:00 CET 2001


m.bless at gmx.de (Martin Bless) wrote:
|To be on the safe side here's what I sometimes use:
|def removecrlf( line):
|    """Remove \r\n or \n from end of string."""
|    if line[-1:] == '\n':
|        if line[-2:-1] == '\r':
|            return line[:-2]
|        else:
|            return line[:-1]
|    else:
|        return line

This is probably not quite safe enough.  MacOS lines end with '\r'.
Adding that case is left as an exercise to readers (I like the regex
version that someone--Skip?--posted in this thread).

Yours, Lulu...




More information about the Python-list mailing list