Python-使用正则表达式将字符串中的单词替换为标题大小写中的相同单词

Python-使用正则表达式将字符串中的单词替换为标题大小写中的相同单词,python,regex,string,replace,Python,Regex,String,Replace,我有下面的字符串。我正在使用re.sub()替换字符串列表中的特定单词/模式。但是,我想以原始形式大写/命名这些替换 mystring = "hello foo and bar. You are foo bar" mywords = ['Foo', 'Bar'] 期望输出: "hello Foo and Bar. You are Foo Bar" 我所尝试的: new = re.sub(rf"({'|'.join(mywords)})", string.capwords(r"\1"), my

我有下面的字符串。我正在使用re.sub()替换字符串列表中的特定单词/模式。但是,我想以原始形式大写/命名这些替换

mystring = "hello foo and bar. You are foo bar"
mywords = ['Foo', 'Bar']
期望输出:

"hello Foo and Bar. You are Foo Bar"
我所尝试的:

new = re.sub(rf"({'|'.join(mywords)})", string.capwords(r"\1"), mystring, flags=re.IGNORECASE)

new2 = re.sub(rf"({'|'.join(mywords)})", (r"\1").title(), mystring, flags=re.IGNORECASE)

尝试使用大写、标题和大写,但都不会改变原始单词的大小写。是否可以使用re.sub()执行此操作?

您可以使用
lambda
替换:

>>> print ( re.sub(rf'({"|".join(mywords)})',
    lambda m: m.group(1).title(), mystring, flags=re.I) )

hello Foo and Bar. You are Foo Bar