简体   繁体   English

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

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

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

I need to replace 'John' and 'Maria'.我需要替换“约翰”和“玛丽亚”。 How can I do this?我怎样才能做到这一点?

I tried:我试过了:

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

But it only works with 'John'.但它只适用于“约翰”。 The output is: 'replaced is hunting, Maria is cooking'. output 是:“被取代的是狩猎,玛丽亚是烹饪”。 How can I replace the two names?如何替换这两个名称?

Thanks.谢谢。

Strings are immutable in python, so replacements don't modify the string, only return a modified string.字符串在 python 中是不可变的,因此替换不会修改字符串,只会返回修改后的字符串。 You should reassign the string:您应该重新分配字符串:

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

You don't need the if name in e_text check since replace already does nothing if it's not found.您不需要if name in e_text因为如果没有找到replace已经什么都不做。

You could form a regex alteration of names and then re.sub on that:您可以对名称进行正则表达式更改,然后对其进行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)

This prints:这打印:

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