cut off \n

Bengt Richter bokr at oz.net
Tue Jun 10 10:31:21 CEST 2003


On Mon, 09 Jun 2003 17:50:37 +0200, Tom <llafba at gmx.net> 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]).
If you are reading the whole file, you could just do
     lines = file('somefile').read().splitlines()

 >>> help(str.splitlines)
 Help on method_descriptor:

 splitlines(...)
     S.splitlines([keepends]) -> list of strings

     Return a list of the lines in S, breaking at line boundaries.
     Line breaks are not included in the resulting list unless keepends
     is given and true.

 >>> 'abc\r\ndef\n3 trailing spaces:   \nend.'.splitlines()
 ['abc', 'def', '3 trailing spaces:   ', 'end.']

Note that the trailing spaces were preserved, but '\r\n' and '\n' were both eliminated.


Others have suggested methods of doing it line by line. Note that you can (ver >=2.2.2 ?)
strip characters from a defined set, not just a single character, or all whitespace:

 >>> help(str.rstrip)
 Help on method_descriptor:

 rstrip(...)
     S.rstrip([sep]) -> string or unicode

     Return a copy of the string S with trailing whitespace removed.
     If sep is given and not None, remove characters in sep instead.
     If sep is unicode, S will be converted to unicode before stripping

 >>> 'abc123\r\n'.rstrip('\n')
 'abc123\r'
 >>> 'abc123\r\n'.rstrip('\n\r')
 'abc123'
 >>> 'abc123\r\n'.rstrip('2\n\r3')
 'abc1'

The default strips whitespace, which might be more than just '\n'

 >>> 'abc123\r\n'.rstrip()
 'abc123'

>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
>

Regards,
Bengt Richter




More information about the Python-list mailing list