cut off \n

Brett g Porter bgporter at artlogic.com
Mon Jun 9 18:08:11 CEST 2003


Andrew Wilkinson wrote:
> Tom wrote:
> 
> 
>>Hi,
> 
> 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.

If there's not going to be any other whitespace at the end of the line 
that you might want to keep, the strip() or rstrip() string methods are 
useful:

 >>> s = "this is a string ending in a newline\n"
 >>> s
'this is a string ending in a newline\n'
 >>> s.strip()
'this is a string ending in a newline'
 >>> s2 = "no newline here!!"
 >>> s2.strip()
'no newline here!!'
 >>> s3 = "   this is a test   \n"
 >>> s3
'   this is a test   \n'
 >>> s3.strip()
'this is a test'
 >>> s3.rstrip()
'   this is a test'
 >>>





More information about the Python-list mailing list