-1

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!

Alexandre FG
  • 43
  • 1
  • 5
  • you should pass one element from replacers to `replace` (which is `str`), not the whole list which is `list` – jsofri Nov 23 '21 at 13:42
  • Similar question: https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string – Adam Feor Nov 23 '21 at 13:42

5 Answers5

2

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)
cotrane
  • 149
  • 4
1

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
Daweo
  • 31,313
  • 3
  • 12
  • 25
1

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
Thekingis007
  • 627
  • 2
  • 16
0

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

mozway
  • 194,879
  • 13
  • 39
  • 75
0

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

Carlos
  • 190
  • 8