John Smith
John Smith

Reputation: 2738

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 ?

Upvotes: 3

Views: 5548

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250981

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'

Upvotes: 4

iomartin
iomartin

Reputation: 3199

You could do

'this is my string\r\nand here it continues'.replace('\r\n', '')

Upvotes: 0

monkut
monkut

Reputation: 43840

cleaned = u"".join([line.strip() for line in u'\r\nFoo\r\nBar, FooBar'.split("\r\n")])

or just use replace():

cleaned = u'\r\nFoo\r\nBar, FooBar'.replace("\r\n", "")

Upvotes: 1

Related Questions