[英]remove white spaces between special characters and words python
我正在尝试删除特殊字符和单词之间的所有空白。
例如,
"My Sister ' s boyfriend is taking HIS brother to the movies . "
至
"My Sister's boyfriend is taking HIS brother to the movies."
如何在Python中做到这一点?
谢谢
诸如删除字符串中多个空格的简单方法之类的简单解决方案? 不起作用,因为它们只是删除重复的空格,因此会在点和引号周围留下空格。
但是可以使用regex简单地完成,使用\\W
来确定非字母数字(包括空格),然后在此之前和之后删除空格(使用\\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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.