Newby: how to transform text into lines of text

John Machin sjmachin at lexicon.net
Sun Jan 25 15:06:48 EST 2009


On Jan 26, 12:54 am, Tim Chase <python.l... at tim.thechases.com> 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
others?

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]

Cheers,
John



More information about the Python-list mailing list