我有一堆像这样的字符串:
t='Enter FLAVIUS , MURELLUS , a CARPENTER , a
COBBLER , and certain other
COMMONERS over the stage ! '
即。多个空格的字符串。 如果应用以下正则表达式,我设法将多个空格转换为仅一个空格,这就是我想要的:
re.sub(' +',' ',t)
OUTPUT: 'Enter FLAVIUS , MURELLUS , a CARPENTER , a COBBLER , and certain other COMMONERS over the stage !'
我现在需要摆脱一个标点符号之间不必要的空格。
换句话说,我希望输出为:
OUTPUT: 'Enter FLAVIUS, MURELLUS, a CARPENTER, a COBBLER, and certain other COMMONERS over the stage!'
我该怎么做?
答案 0 :(得分:1)
import re
t='Enter FLAVIUS , MURELLUS , a CARPENTER , a COBBLER , and certain other COMMONERS over the stage ! '
print(re.sub('\s+(?=[!,])','',re.sub(' +',' ',t)))
输出
Enter FLAVIUS, MURELLUS, a CARPENTER, a COBBLER, and certain other COMMONERS over the stage!