python - 删除某些字符集后的空格
问题描述
例如,我想更改以下字符串
strr = 'Hello, this is a test to remove whitespace.'
至
'Hello,this is a testto removewhitespace.'
因此,应删除逗号、“t”或“e”字符后的空格。我试过类似的东西:
re.sub(', |t |e ', ' ', strr)
但是,这也会删除逗号、t 和 e。之后,我试图在剩余的空格上拆分字符串。我的第一种方法是像这样拆分
re.split(' is |a |test|remove', strr)
但是,这也删除了分隔符,这不是我想要实现的。所以基本上,我想提供一个后跟空格的字符列表,以便删除该子字符串中的空格。
解决方案
就像是:
import re
str1 = 'Hello, this is a test to remove whitespace.'
str2 = re.sub(r'([te,])\s+', r'\1', str1)
print(str2)
应该可以工作,您匹配(和捕获)一个已知组,然后是任意数量的空格,并用您捕获的内容替换整个内容。
推荐阅读
- java - 为什么“public”会给我一个未解决的编译问题?
- c# - MahApps 上下文未在启动时注册
- neo4j - 如何使用java在neo4j中的数据库之间切换
- java - 如何在矩形的水平线上找到索引?
- pyspark - AWS EMR spark: org.apache.hadoop.security.AccessControlException: Permission denied: user=livy, access=WRITE, inode="/":hdfs:hdfsadmingroup:drwxr-xr-x
- ios - 后台任务iOS不触发本地通知
- java - 比较列表的所有成员
- vue.js - vuepress vue提示和文件夹结构
- javascript - 动态地将类添加到字符串中的单词Angular
- python - 如何创建一个独立的非模态对话框