2012-03-09 25 views
0

我試圖凝聚/改善/優化該代碼的stripslashes問題

cleaned = stringwithslashes 
cleaned = cleaned.replace("\\n", "\n") 
cleaned = cleaned.replace("\\r", "\n") 
cleaned = cleaned.replace("\\", "") 

,但上面的代碼不能正常工作

+2

呃,爲什麼這個標記爲PHP? – animuson 2012-03-09 05:33:44

+0

這不是PHP,除非它的一些模板語言... – prodigitalson 2012-03-09 05:34:24

+0

當你想要非轉義的反斜槓時使用'r'raw strings'。並且第2,3行有語法錯誤(沒有收盤引號?) – wim 2012-03-09 05:42:07

回答

0

試試這個

cleaned = stringwithslashes.decode('string_escape') 
+0

錯誤,什麼?參考這個? – 2012-03-09 05:35:09

+0

這僅適用於Python 2.使用Python 3時,它不再適用。 – nerdoc 2017-05-08 20:07:30

1

對於初學者你的代碼缺少引號。你試過這個嗎?

cleaned = stringwithslashes 
cleaned = cleaned.replace("\\n", "\n") 
cleaned = cleaned.replace("\\r", "\n") 
cleaned = cleaned.replace("\\", "")