我正在尝试删除特殊字符和单词之间的所有空格。
例如,
"My Sister ' s boyfriend is taking HIS brother to the movies . "
到
"My Sister's boyfriend is taking HIS brother to the movies."
如何在Python中执行此操作?
谢谢
答案 0 :(得分:3)
像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.