Stripping new lines from strings?

Alex Martelli alex at magenta.com
Tue Aug 15 04:12:25 EDT 2000


"CHRIS" <unk at unk.ororr> wrote in message news:3998E9CB.3CB3FBA6 at unk.ororr...
> What is the best (fastest) way to strip new line characters from a
> string in Python? In C I would do:
>
> char *p;
> p = strchr(str, '\n');
> if(p)
>   *p = '\0';
>
> /* repeat process for '\r' character */

If you have to remove more than one kind of character, and particularly
if you don't know beforehand how many of each kind to remove (so that
a loop might be needed), I think that, for speed, you can't beat the
little-known
string.translate method.


It's super if you also have to do some char-to-char translation, but,
even if you don't, this works:

# once only...:
import string
identity=string.maketrans('','')

# then, every time you need to eliminate characters:
str=string.translate(str,identity,'\n\r')


Alex






More information about the Python-list mailing list