stripping cr/lf, lf, cr

Steve Purcell stephen_purcell at yahoo.com
Tue Mar 27 11:21:47 EST 2001


deadmeat wrote:
> Is there a platform independant function that will remove appropriate EOL
> characters from a string?  I don't want to use strip() since it will also
> remove other whitespace I want to keep.
> 

No, but it's easy to write one:

>>> import string, os
>>> def strip_eol(s):
...    pos = string.rfind(s, os.linesep)
...    if pos == -1: return s
...    if pos < len(s) - len(os.linesep):
...       return s
...    return s[:-len(os.linesep)]
... 
>>> os.linesep  
'\012'
>>> strip_eol('a line\n')
'a line'
>>> strip_eol('a line')
'a line'
>>> strip_eol('a \nline')
'a \012line'
>>> strip_eol('a \nline\n')
'a \012line'
>>> strip_eol('a line\r\n')
'a line\015'


-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list