Newby: how to transform text into lines of text

John Machin sjmachin at
Sun Jan 25 21:06:48 CET 2009

On Jan 26, 12:54 am, Tim Chase <python.l... at> wrote:

> One other caveat here, "line" contains the newline at the end, so
> you might have
>   print line.rstrip('\r\n')
> to remove them.

I don't understand the presence of the '\r' there. Any '\x0d' that
remains after reading the file in text mode and is removed by that
rstrip would be a strange occurrence in the data which the OP may
prefer to find out about and deal with; it is not part of "the
newline". Why suppress one particular data character in preference to

The same applies in any case to the use of rstrip('\n'); if that finds
more than one ocurrence of '\x0a' to remove, it has exceeded the
mandate of removing the newline (if any).

So, we are left with the unfortunately awkward
    if line.endswith('\n'):
        line = line[:-1]


More information about the Python-list mailing list