2013-09-21 130 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

相關問題