2017-08-30 69 views
0

我試圖刪除此字符串中的所有"\n"。然而,string.strip()方法並不能完全清除文本strip()並非全部替換 n

body = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSome text\n\nHow toremovealln?\n\t\t\t\t\tbecause notworking\n\t\t\t\t\t" 
body.strip("\n") 

結果是

"Some text\n\nHow toremovealln?\n\t\t\t\t\tbecause notworking\n\t\t\t\t\t" 

如何將它們全部刪除?

+0

你的問題是什麼? –

+5

'strip'只能去掉前後的字符 – Wondercricket

+0

那麼你到底需要輸出什麼? –

回答

0

使用string.replace替換 '\ n' 爲 ''(空字符串):

body = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSome text\n\nHow toremovealln?\n\t\t\t\t\tbecause notworking\n\t\t\t\t\t" 
print(body.replace('\n', '')) 
+0

@ J.Doe,你能證明這一點嗎? 'replace()'不起作用(儘管文檔說明它應該),而'strip()'不起作用的目的是違反其文檔,這更令人驚訝。 –

+0

你可以測試這兩行代碼,並給我輸出?爲我工作;) –

0

使用string.replace()沒有strip

這種方法將用新char更換舊char。在你的情況下,你想'new line'\n''替換'沒有''。正如下面

body.replace('\n', '')

看到了這將返回一個新string,你可以重新分配到體:

body = body.replace('\n', '')

現在body是:

'Some textHow toremovealln?\t\t\t\t\tbecause notworking\t\t\t\t\t'

所以如果你最終想刪除tabs'\t'你可以做進一步的string.replace()他們作爲你上面說:

body = body.replace('\t', '')

0

如果你想只刪除複製換行符,您可以通過re.sub使用正則表達式:

re.sub(r'([\n])\1+', '', body)) 

或刪除他們都:

re.sub(r'\n', '', body) 
1

你分別用''和''替換'\ n'和'\ t'。所以你可以用

 body1 = body.replace("\n",'') 
    body2 = body1.replace("\t",' ') 
+0

'body.replace(「\ n」,「」).replace(「\ t」,「」)''一個班輪也會好看:) –