【问题标题】:remove special character from string in python从python中的字符串中删除特殊字符
【发布时间】:2020-06-06 14:55:34
【问题描述】:
就像我有字符串变量,其值如下所示
string_value = 'hello ' how ' are - you ? and/ nice to % meet # you'
预期结果:
你好,很高兴认识你
【问题讨论】:
标签:
python-3.x
string
special-characters
【解决方案1】:
您可以尝试只删除所有非单词字符:
string_value = "hello ' how ' are - you ? and/ nice to % meet # you"
output = re.sub(r'\s+', ' ', re.sub(r'[^\w\s]+', '', string_value))
print(string_value)
print(output)
打印出来:
hello ' how ' are - you ? and/ nice to % meet # you
hello how are you and nice to meet you
我首先使用的解决方案使用[^\w\s]+ 模式针对所有非单词字符(空格除外)。但是,有可能会留下两个或更多空间的集群。因此,我们再次调用 re.sub 以删除多余的空格。