Problem stripping line feeds

Tony Meyer t-meyer at ihug.co.nz
Sun Jul 25 04:00:03 CEST 2004


> I am using the following function to try and strip both 
> carraige returns and line feeds, ASCII 13 and 10 
> respectively, from a string.  It doesn't seem to be working:
> 
> x = filter(lambda c: c not in "\012\015", string.strip(x)) # 
> octal version
> 
> I also tried:
> 
> x = filter(lambda c: c not in "\r\n", string.strip(x)) # 
> escape char. version
> 
> What am I doing wrong?

Like Roel, this works for me.  Couple of things:

 1.  Avoid doing string.strip(x) - use x.strip() instead.
 2.  Using replace() is a lot more straightforward than using filter and
lambda.  It appears to be (a lot) faster, too:

>>> import timeit
>>> t1 = timeit.Timer(r"s.replace('\r', '').replace('\n', '')", r"s = 'This
is a sample \r string with \n various \r end of line \r characters \n\r\n'")
>>> t1.timeit()
4.1181809419912305
>>> t2 = timeit.Timer(r"filter(lambda c: c not in '\r\n', s.strip())", r"s =
'This is a sample \r string with \n various \r end of line \r characters
\n\r\n'")
>>> t2.timeit()
54.062190865040108

=Tony Meyer




More information about the Python-list mailing list