用名称替换标题

2024-09-27 18:09:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串:

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

如何修复代码?谢谢你的帮助


Tags: namenewhereismatchmdpersongood
2条回答

re.sub与捕获组一起使用:

>>> import re
>>> st = "Dee Fee, MD is a good person. Kas Egre, MD came here"
>>> rename = re.compile(r'([A-Z][a-z]+\s+[A-Z][a-z]+),\s*\bMD\b')
>>> rename.sub(r'Name: \1', st)
'Name: Dee Fee is a good person. Name: Kas Egre came here'

替换字符串中的\1被替换为第一个捕获的组(名称部分)。你知道吗

把正则表达式简化一点。。。你知道吗

>>> re.sub(r'(\w+\s+\w+),\s*MD', lambda x: 'Name: '+ x.group(1), st)
'Name: Dee Fee is a good person. Name: Kas Egre came here'

实际上,这里甚至不需要函数,因为我们可以插入带有\N(其中N是组号)的组。。。你知道吗

>>> re.sub(r'(\w+\s+\w+),\s*MD', r'Name: \1', st)
'Name: Dee Fee is a good person. Name: Kas Egre came here'

相关问题 更多 >

    热门问题