首页 > 解决方案 > 从python中的字符串中删除特殊字符

问题描述

就像我有下面给出的值的字符串变量

string_value = 'hello ' how ' are - you ? and/ nice to % meet # you'

预期结果:

你好,你好吗,很高兴认识你

标签: python-3.xstringspecial-characters

解决方案


您可以尝试仅删除所有非单词字符:

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以删除多余的空格。


推荐阅读