Python去除Unicode和`\r\n`字符

3
我希望能将字符串中的`\r\n'字符去除。为此,我尝试了以下方法:
s1.translate(dict.fromkeys(map(ord, u"\n\r")))
    lists1=[]
    lists1.append(s1)
    print lists1

我收到了以下内容:
[u'\r\nFoo\r\nBar, FooBar']

如何在字符串中去除\r\n字符?


“get rid of the unicode” 是什么意思? - Keith
3个回答

4
使用 str()replace() 函数来移除 u\r\n
In [21]: strs = u'\r\nFoo\r\nBar'

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

或者只需使用 replace() 来仅替换 \r\n

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

我认为你不需要先转换为字符串。 - Keith
OP说他也想在标题中去掉 u - Ashwini Chaudhary
哦,我明白了。但是...这实际上涉及到一种编码,这里隐式地使用了“ascii”编码。但是OP开始使用的是Unicode字面量。 - Keith
谢谢,如果文本中'\n'和'\r'分开的情况怎么办?这种情况下,如何去掉'\n'和'\r'? - John Smith
@JohnSmith,那么你需要像这样使用两个replace函数:strs.replace("\r","").replace("\n","") - Ashwini Chaudhary

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

或者只需使用replace()

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

谢谢,如果字符串中'\n'和'\r'是分离的,该怎么去掉它们呢? - John Smith

0
你可以这样做。
'this is my string\r\nand here it continues'.replace('\r\n', '')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接