Entry
What is the best (fastest) way to strip new line characters from a string in Python?
Aug 16th, 2000 02:56
unknown unknown, Richard Chamberlain, Alex Martelli
Presuming you don't want any space at the end you can use string.strip
so...
import string
p="I line with a newline.\n"
q=string.rstrip(p)
or you could use string.replace
q=string.replace(p,'\n','')
so that would replace the newline character(s) with nothing.
------------------------
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')