fsimoes
fsimoes

Reputation: 79

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'. How can I replace the two names?

Thanks.

Upvotes: 3

Views: 53

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522719

You could form a regex alteration of names and then re.sub on that:

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

Upvotes: 2

Aplet123
Aplet123

Reputation: 35560

Strings are immutable in python, so replacements don't modify the string, only return a modified string. 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.

Upvotes: 4

Related Questions