问题陈述:
Inserts an extra space after a period if the period is directly followed by a letter.
下面是代码:
string="This is very funny and cool.Indeed!"
re.sub("\.[a-zA-Z]", ". ", string)
和输出:
"This is very funny and cool. ndeed!"
它正在替换 '.'
之后的第一个字符。
有什么解决办法吗?
最佳答案
您可以使用positivie lookahead assertion ,它不消耗匹配的部分:
>>> re.sub(r"\.(?=[a-zA-Z])", ". ", string)
'This is very funny and cool. Indeed!'
替代使用 capturing group and backreference :
>>> re.sub(r"\.([a-zA-Z])", r". \1", string) # NOTE - r"raw string literal"
'This is very funny and cool. Indeed!'
仅供引用,您可以使用 \S
而不是 [a-zA-Z] 来匹配非空格字符。
关于python - 使用 re.sub() 的输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26040093/