2017-08-02 60 views
-3

我試圖用傳入行的命令替換所有回車符。它工作正常,除了多個回車存在時。在python的string.replace()函數中,我沒有看到關於如何處理同一項目的多個實例的信息,就好像它們是一樣。這可能嗎?Python替換 - 將多個實例視爲一個

例如,該行:

This is\nA sentence\nwith multiple\nbreaklines\n\npython. 

應該結束了這樣的:

This is, A sentence, with multiple, breaklines, python. 

但它實際上變成這樣:

This is, A sentence, with multiple, breaklines, , python. 
+0

這將有助於確定您的代碼實際看到它的問題。 –

+0

您可以隨時手動迭代列表並替換它們。一個正則表達式在這裏也可能有用。 – Carcigenicate

+0

@Carcigenicate是正確的:使用正則表達式,將任意數量的換行符視爲單個匹配:「\ n」+ – Prune

回答

2

您可以使用正則表達式。

In [48]: mystr = "This is\nA sentence\nwith multiple\nbreaklines\n\npython." 
In [49]: re.sub(r'\n+', ', ', mystr) 
Out[49]: 'This is, A sentence, with multiple, breaklines, python.' 

正則表達式模式匹配,其中有一個或一個以上\n的彼此相鄰並與,替換它們。