Py学习  »  Python

在python中从字符串中删除特殊字符

Umair Mubeen • 6 年前 • 2225 次点击  

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

预期结果:

你好,你好,很高兴见到你

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55138
文章 [ 1 ]  |  最新文章 6 年前
Tim Biegeleisen
Reply   •   1 楼
Tim Biegeleisen    6 年前

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

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