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

Python 正则表达式从字符串中删除换行符,python,regex,Python,Regex,我正在使用python,需要一种快速方法来删除字符串中的所有实例。为了清楚起见,这里有一个我想要的例子 "I went \n to the store\n" 变成 "I went to the store" 我想也许正则表达式是最好的方法。使用str.replace: >>> "I went \n to the store\n".replace('\n', '') 'I went to the store' 对于相等间距,您可以先使用str.split拆分字符串,然后使

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

"I went \n to the store\n"
变成

"I went to the store"

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

使用
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'

我认为正则表达式在这里可能有点过分了。实际上,我想在比示例字符串长得多的大约600万个字符串(我可能应该提到这一点)上执行此操作。所以我建议用正则表达式来表示速度,但这可能还是有点过头了字符串有多长?因为虽然我怀疑正则表达式是否会更快,但是如果字符串很长,您可能需要使用更快的语言或Python的快速实现。因此.split()会删除\n的?@user1893354是的,它会删除所有类型的whitespacesCool,我不知道。谢谢