Idiomatic portable way to strip line endings?

John Roth johnroth at ameritech.net
Sun Dec 16 17:11:49 CET 2001


"Tim Hammerquist" <tim at vegeta.ath.cx> wrote in message
news:slrna1pbik.6jf.tim at vegeta.ath.cx...
> I've been trying to figure out the canonical way to strip the line
> endings from a text file.
>
> In general, I can use:
>
>     line = line[:-1]
> or
>     del line[-1:]
>
> to strip the last character off the line, but this only works on
> operating systems that have a one-byte line separator like Unix/Linux
> ('\n').  The Win32 line separator is 2-bytes ('\r\n'), so this
> solution is not portable.

Huh? This works fine on Windows. The C library (which is
what Python is based on, after all) is defined to convert the
operating system dependent line end sequence to '\n'
on input, and back on output.

John Roth






More information about the Python-list mailing list