John Smith John Smith - 3 months ago 10
Python Question

python get rid of unicode and `\r\n` characters

I want to get rid `\r\n' characters in my string to do so, I tried this :

s1.translate(dict.fromkeys(map(ord, u"\n\r")))
lists1=[]
lists1.append(s1)
print lists1


I received this:

[u'\r\nFoo\r\nBar, FooBar']


How can I get rid of
\r\n
characters in my string ?

Answer

Use str() and replace() to remove both u and \r\n:

In [21]: strs = u'\r\nFoo\r\nBar'

In [22]: str(strs).replace("\r\n","")
Out[22]: 'FooBar'

or just replace() to get rid of only \r\n:

In [23]: strs.replace("\r\n","")
Out[23]: u'FooBar'