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

How to replace a list of strings of a string?

如何使用下面代码中的字符串列表获取字符串“Hello World”? 我正在尝试:

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

str1.replace(replacers, "")

导致此错误的结果:

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

有什么建议吗?提前致谢!

您需要重复使用 .replace 例如使用 for 循环

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

输出

Hello World

你应该遍历你的替换列表试试这个解决方案:

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

输出:

Hello World

一种不需要再次阅读每个替换字符串的有效方法是使用正则表达式:

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

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

输出:Hello World

replace 仅将字符串作为其第一个参数,而不是字符串列表。

您可以遍历要替换的各个子字符串:

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

或者您可以使用正则表达式来执行此操作:

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

您可以使用正则表达式,但这取决于您的用例,例如:

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

在你的例子中创建这个正则表达式:(XX)|(YYY) 那么你可以使用 re.sub:

re.sub(regex, "", a)

备选方案可能只是使用 for 循环并替换 replacers

中的值