正则表达式从字符串中删除换行符

时间:2013-09-21 18:07:39

标签: python regex

我正在使用python,我需要一种快速的方法来删除字符串中的\ n的所有实例。为了清楚起见,这是我想要的一个例子。

"I went \n to the store\n"

变为

"I went to the store"

我想也许正则表达式是最好的方式。

1 个答案:

答案 0 :(得分:8)

使用str.replace

>>> "I went \n to the store\n".replace('\n', '')
'I went  to the store'

对于相等的间距,您可以先使用str.split拆分字符串,然后使用str.join将其连接回来:

>>> ' '.join("I went \n to the store\n".split())
'I went to the store'