Home > OS >  How to replace a list of strings of a string?
How to replace a list of strings of a string?

Time:11-24

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!

CodePudding user response:

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

CodePudding user response:

You need to repeatedly use .replace for example using for loop

str1="HellXXo WoYYrld"
replacers = ["YY", "XX"]
for rep in replacers:
    str1 = str1.replace(rep, "")
print(str1)

output

Hello World

CodePudding user response:

you should iterate through your list of replacers Try This solution:

str1="HellXXo WoYYrld"
replacers = ["YY", "XX"]
for elem in replacers:
  str1=str1.replace(elem, "")
  
print(str1)

Output:

Hello World

CodePudding user response:

replace takes only a string as its first argument and not a list of strings.

You can either loop over the individual substrings you want to replace:

str1="HellXXo WoYYrld"
replacers = ["YY", "XX"]
for s in replacers:
  str1 = str1.replace(s, "")
print(str1)

or you can use regexes to do this:

import re
str1="HellXXo WoYYrld"
replacers = ["YY", "XX"]
re.sub('|'.join(replacers), '', str1)

CodePudding user response:

you could use a regex but it depends of your use case for example:

 regex = r"("  ")|(".join(replacers)  ")"

in your case creates this regular expression: (XX)|(YYY) then you could use re.sub:

re.sub(regex, "", a)

the alternative could be just use a for loop and replace the values in replacers

  • Related