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字符串中的字符?

4

3 回答 3

4

使用str()andreplace()删除uand \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'
于 2012-11-02T02:03:26.453 回答
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", "")
于 2012-11-02T02:03:22.353 回答
0

你可以做

'this is my string\r\nand here it continues'.replace('\r\n', '')
于 2012-11-02T02:05:29.857 回答