Idiomatic portable way to strip line endings?

Martin Bless m.bless at
Sun Dec 16 19:03:52 CET 2001

[Tim Hammerquist]:

>Ah. So I was doing my normal over-thinking again.  =)

Yes - and it's totally appropriate. Danger is not over.

The line[:-1] idiom works fine on windows, as long you (can) garantee
that files are opened without the "b" (binary) mode switch.
If the file is opened 'binary', as in 
  fp = open(fname,'rb')
no input conversion will be done by the lower level routines. This
means your line endings are '\r\n' indeed on a windows system.

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]
            return line[:-1]
        return line

More information about the Python-list mailing list