我有一个字符串:
st = "Dee Fee, MD is a good person. Kas Egre, MD came here"
我想用"Name:"
替换", MD"
,并将其放在name之前,因此新字符串应该是:
new = "Name: Dee Fee is a good person. Name: Kas Egre came here"
我写了下面的代码,它的作品,但它没有给我想要的。结果是:
Name: Dee Fee, MD is a good person. Name: Dee Fee, MD came here
Name: Kas Egre, MD is a good person. Name: Kas Egre, MD came here
这是我的密码:
rename = re.compile(r"""([A-Z][a-z]+\s[A-Z\s]*[A-Z][a-z]+)(,\s)(MD)""")
match = rename.search(st)
for match in rename.finditer(st):
if match.group(3) == 'MD':
new = rename.sub("Name: %s"%(match.group(0)),st)
print new
如何修复代码?谢谢你的帮助
将
re.sub
与捕获组一起使用:替换字符串中的
\1
被替换为第一个捕获的组(名称部分)。你知道吗把正则表达式简化一点。。。你知道吗
实际上,这里甚至不需要函数,因为我们可以插入带有
\N
(其中N是组号)的组。。。你知道吗相关问题 更多 >
编程相关推荐