0
我試圖刪除特殊字符和單詞之間的所有空格。刪除特殊字符和單詞之間的空格python
例如,
"My Sister ' s boyfriend is taking HIS brother to the movies . "
到
"My Sister's boyfriend is taking HIS brother to the movies."
如何做到這一點在Python?
謝謝
我試圖刪除特殊字符和單詞之間的所有空格。刪除特殊字符和單詞之間的空格python
例如,
"My Sister ' s boyfriend is taking HIS brother to the movies . "
到
"My Sister's boyfriend is taking HIS brother to the movies."
如何做到這一點在Python?
謝謝
像Simple way to remove multiple spaces in a string?簡單的解決方案不起作用,因爲他們只是刪除重複的空間,所以它的周圍留下點和報價的空間。
但能後&前簡單地完成,用正則表達式,使用\W
確定非alphanum(包括空格),並刪除空格(使用\s*
不\s+
所以它可以處理開始字符串的&結束,而不是令人滿意因爲它執行同樣的事情有很多替代品,但簡單&做這項工作):
import re
s = "My Sister ' s boyfriend is taking HIS brother to the movies ."
print(re.sub("\s*(\W)\s*",r"\1",s))
結果:
My Sister's boyfriend is taking HIS brother to the movies.
謝謝!但我仍然有電影和電影之間的空白。 :(( – hhhh
編輯,最後處理點沒有空格,你的問題不是這樣,不管怎麼說,即使它用點結尾也是有效的。 –