【问题标题】:remove white spaces between special characters and words python删除特殊字符和单词python之间的空格
【发布时间】:2018-04-24 13:25:46
【问题描述】:

我正在尝试删除特殊字符和单词之间的所有空格。

例如,

"My Sister  '  s boyfriend is taking HIS brother to the movies  .  " 

"My Sister's boyfriend is taking HIS brother to the movies." 

如何在 Python 中做到这一点?

谢谢

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    Simple way to remove multiple spaces in a string? 之类的简单解决方案不起作用,因为它们只是删除重复的空格,因此会在点和引号周围留下空格。

    但是可以使用正则表达式简单地完成,使用\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.
    

    【讨论】:

    • 谢谢!但我仍然在电影和. :((
    • 已编辑,处理点最后没有空格。你的问题不是这种情况。无论如何,现在即使它以点结尾也有效。