繁体   English   中英

如何使用列表替换字符串的某些部分?

[英]How to replace certain parts of a string using a list?

namelist = ['John', 'Maria']
e_text = 'John is hunting, Maria is cooking'

我需要替换“约翰”和“玛丽亚”。 我怎样才能做到这一点?

我试过了:

for name in namelist:
    if name in e_text:
        e_text.replace(name, 'replaced')

但它只适用于“约翰”。 output 是:“被取代的是狩猎,玛丽亚是烹饪”。 如何替换这两个名称?

谢谢。

字符串在 python 中是不可变的,因此替换不会修改字符串,只会返回修改后的字符串。 您应该重新分配字符串:

for name in namelist:
    e_text = e_text.replace(name, "replaced")

您不需要if name in e_text因为如果没有找到replace已经什么都不做。

您可以对名称进行正则表达式更改,然后对其进行re.sub

namelist = ['John', 'Maria']
pattern = r'\b(?:' + '|'.join(namelist) + r')\b'
e_text = 'John is hunting, Maria is cooking'
output = re.sub(pattern, 'replaced', e_text)
print(e_text + '\n' + output)

这打印:

John is hunting, Maria is cooking
replaced is hunting, replaced is cooking

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM