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!
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
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
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
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.