2013-09-21 132 views
1

我正在使用python,我需要一种快速的方式来删除字符串中的\ n的所有实例。只是要清楚,这是我想要的一个例子。正则表达式从字符串中删除换行符

"I went \n to the store\n" 

成为

"I went to the store" 

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

+0

我想正则表达式可能是矫枉过正这里。 – rlms

+0

我实际上想要在大约6百万个字符串(我可能应该提到过)比这个例子字符串长得多。所以我建议正则表达式的速度,但它仍然可能是矫枉过正 – user1893354

+0

字符串有多长?因为虽然我怀疑正则表达式会更快,但是如果字符串很长,您可能需要使用更快的语言或Python的快速实现。 – rlms

回答

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' 
+0

那么.split()会删除\ n's? – user1893354

+0

@ user1893354是的,它删除所有类型的空格 –

+0

酷,我不知道。谢谢! – user1893354

相关问题