cut off \n

sismex01 at sismex01 at
Mon Jun 9 17:53:47 CEST 2003

> From: Tom [mailto:llafba at]
> Sent: Monday, June 09, 2003 10:51 AM
> Hi,
> I have to read data from a file to a list. Unfortunately most of the 
> data that I read into my little list ends with a linefeed \n.
> Right now I get rid of this by just cutting off the last 
> character. (a = > l[:-1]).

This is *almost* the correct way to do it :-)

> My problem is that sometimes the last line of the file has a \n and 
> sometimes not. With the method above I sometimes cut off parts of my 
> string. So it would be much nicer if I can find out if the data does 
> have a \n and then cut it off.

You could do somethint like:

    if line.endswith("\n"):
        line = line[:-1]

or, if trailing whitespace is not significant (you don't mention it),
you can also do something like:

    line = line.rstrip()

or, if leading whitespace is not significant either, you can also
trim all leading and trailing whitespace, thusly:

    line = line.strip()

> This is probably a very common problem but I am pretty new to Phython 
> and could find anything useful with google. :-(
> Thanks, Tom

Perl has yet-another-kinda-useful-function called "chomp", which
deletes a line ending from a string, only if it's found.  Alas,
python is chompless, not that I'm complaining, the above code
is what I use all the time.


Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.

More information about the Python-list mailing list