【问题标题】:How to replace a list of strings of a string?如何替换字符串的字符串列表?
【发布时间】:2022-01-02 00:12:02
【问题描述】:

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

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

str1.replace(replacers, "")

导致此错误的原因:

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

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

【问题讨论】:

标签: python string replace


【解决方案1】:

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

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

输出

Hello World

【讨论】:

    【解决方案2】:

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

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

    输出:

    Hello World
    

    【讨论】:

      【解决方案3】:

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

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

      输出:Hello World

      【讨论】:

        【解决方案4】:

        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)
        

        【讨论】:

          【解决方案5】:

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

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

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

          re.sub(regex, "", a)
          

          替代方法可以只使用 for 循环并替换替换器中的值

          【讨论】:

            猜你喜欢
            • 2021-05-22
            • 2013-05-01
            • 2017-06-22
            • 1970-01-01
            • 1970-01-01
            • 2019-05-13
            • 2021-12-19
            • 1970-01-01
            • 2012-08-18
            相关资源
            最近更新 更多