假设我用字符串“Taco>Bell”读入了一个输入文件,我想用“Taco>”和“Bell”替换那个字符串。换句话说,我想用两个替换一个字符串。我知道如何使用带有正则表达式的 split 方法来拆分字符串,但是如何执行替换呢?
每次有一个字符串有一个 ">" 后跟一个非空格字符,我想在字符之间插入一个空格。
在这种情况下,您需要向前看,如下所示:
import re
mystring = "John likes to eat Taco>Bell because it is Bar>Foo healthy third> ok."
print mystring
mystring = re.sub(r">(?! )", "> ", mystring)
print mystring
>
基本上,只有在 之后的字符不是空格时才会发生替换。
输出:
John likes to eat Taco>Bell because it is Bar>Foo healthy third> ok.
John likes to eat Taco> Bell because it is Bar> Foo healthy third> ok.
一个可能的非正则表达式解决方案是
>>> somestr.replace(">","> ").replace("> ","> ")
'John likes to eat Taco> Bell because it is Bar> Foo healthy third> ok.'