python - 用名称替换标题

标签 python python-2.7

我有一个字符串:

st = "Dee Fee, MD is a good person. Kas Egre, MD came here"

我想将 ", MD" 替换为 "Name:" 并将其放在 name 之前,因此新字符串应该是:

new = "姓名:Dee Fee 是个好人。姓名:Kas Egre 来到这里"

我编写了以下代码,它可以工作,但它没有给出我想要的。结果是这样的:

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(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'

关于python - 用名称替换标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22087165/

相关文章:

python - 类型错误 : unbound method decode() must be called with JSONDecoder instance as first argument (got PrintJson instance instead)

python - 我如何在 python 中使用 pcov 来获取每个参数的错误?

python - 如何在Python中使用 "svgwrite"库创建动画

python - 防止导入的模块出现在代码完成中?

Python-从多个列表中查找不匹配的值

python - 无法填充 QTableWidget

python - 用 python regexp 只替换一个字符的单个实例

Python、Django、日期时间

超过 24 小时的 Python 时间对象

python_2_unicode_compatible 错误