首页 > 解决方案 > 删除某些字符集后的空格

问题描述

例如,我想更改以下字符串

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)

但是,这也删除了分隔符,这不是我想要实现的。所以基本上,我想提供一个后跟空格的字符列表,以便删除该子字符串中的空格。

标签: pythonregexsplitsubstringwhitespace

解决方案


就像是:

import re

str1 = 'Hello, this is a test to remove whitespace.'

str2 = re.sub(r'([te,])\s+', r'\1', str1)

print(str2)

应该可以工作,您匹配(和捕获)一个已知组,然后是任意数量的空格,并用您捕获的内容替换整个内容。


推荐阅读