cut off \n
Andrew Wilkinson
ajw126 at NOSPAMyork.ac.uk
Mon Jun 9 12:00:37 EDT 2003
Tom wrote:
> 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]).
> 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.
>
> This is probably a very common problem but I am pretty new to Phython
> and could find anything useful with google. :-(
>
> Thanks, Tom
def remove_last_newline(line):
if line[-1] == "\n":
return line[:-1]
else:
return line
newlist = map(remove_last_newline, yourlist)
Unfortunatly without a single line if-expression in Python I can't think of
a single line solution to this problem.
Hope this is of use,
Andrew Wilkinson
More information about the Python-list
mailing list