How to replace a list of strings of a string?

How can I get the string "Hello World" using a list of strings in the code below?
I’m trying:

str1="HellXXo WoYYrld"
replacers = ["YY", "XX"]

str1.replace(replacers, "")

Which results in this error:

TypeError: replace() argument 1 must be str, not list

Any suggestion? Thanks in advance!

>Solution :

An efficient method that won’t require to read again the string for each replacer is to use a regex:

str1="HellXXo WoYYrld"
replacers = ["YY", "XX"]

import re
re.sub('|'.join(replacers), '', str1)

output: Hello World

Leave a Reply