简体   繁体   English

如何替换字符串的字符串列表?

[英]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?如何使用下面代码中的字符串列表获取字符串“Hello World”? 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您需要重复使用.replace例如使用for循环

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

output 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: 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 output: Hello World

replace takes only a string as its first argument and not a list of strings. replace只接受一个字符串作为它的第一个参数,而不是一个字符串列表。

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:在你的情况下创建这个正则表达式: (XX)|(YYY)然后你可以使用 re.sub:

re.sub(regex, "", a)

the alternative could be just use a for loop and replace the values in replacers替代方法可能只是使用 for 循环并替换替换器中的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM