让我说我在输入文件中读到字符串" Taco> Bell"我想用" Taco>"替换那个String。和贝尔"。换句话说,我想用一个String替换一个String。我知道如何使用带有正则表达式的split方法来拆分String,但是如何执行替换?
每次有一个字符串,其中包含">"后跟一个非空格字符,我想在字符之间插入一个空格。
答案 0 :(得分:1)
在这种情况下,你需要展望未来,如下:
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.
答案 1 :(得分:0)
可能的非正则表达式解决方案
>>> somestr.replace(">","> ").replace("> ","> ")
'John likes to eat Taco> Bell because it is Bar> Foo healthy third> ok.'