python-3.x - 从python中的字符串中删除特殊字符
问题描述
就像我有下面给出的值的字符串变量
string_value = 'hello ' how ' are - you ? and/ nice to % meet # you'
预期结果:
你好,你好吗,很高兴认识你
解决方案
您可以尝试仅删除所有非单词字符:
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
以删除多余的空格。
推荐阅读
- reactjs - componentDidUpdate 不断被调用
- reactjs - React:如何在 AddListener() 中使用 setState?
- java - 更改 DatePicker DayCell 颜色
- java - ResulSet web 服务调用错误resulset close
- javascript - 我可以隐藏我的平均菜单 jquery 的文本和按钮吗?
- sql - 计算sql过程中给定日期范围的百分比
- django - 如何在 Python 中迭代 json 对象?
- python - 如何为 Netmiko 访问的 if/else 输出创建每个 for 循环的专用文件
- python - 在 python 中如何使用选定的 Outlook 电子邮件
- java - RepositoryException:org.sql2o.Sql2oException:数据库错误:查询未返回任何结果