【问题标题】:Replace a substring in a string according to a list根据列表替换字符串中的子字符串
【发布时间】:2019-11-08 18:42:53
【问题描述】:

根据教程点:

replace() 方法返回字符串的副本,其中出现的 old 已替换为 new。 https://www.tutorialspoint.com/python/string_replace.htm

因此可以使用:

>>> text = 'fhihihi'
>>> text.replace('hi', 'o')
'fooo'

有了这个想法,给定一个列表[1,2,3]和一个字符串'fhihihi',有没有一种方法可以将子字符串hi依次替换为1、2和3?例如,这个理论解决方案会产生:

'f123'

【问题讨论】:

    标签: python list replace


    【解决方案1】:

    您可以使用初始字符串创建format string

    >>> text = 'fhihihi'
    >>> replacement = [1,2,3]
    >>> text.replace('hi', '{}').format(*replacement)
    'f123'
    

    【讨论】:

    • 不错的一个 - 只要我们没有像 text = 'fhihi{hi' 这样失败的 ValueError: Single '}' encountered in format string...
    • 我尝试使用 timeit,这个解决方案比 re.sub 和我的幼稚解决方案快 3 倍。您只需要使用 range 创建替换列表即可进行缩放,因为您不知道字符串是否包含 3 个 his 或更多。
    • 你说的都对,这段代码仅在文本不包含{}或与replacement长度不同的hi的数量的假设下有效列表。但是使用range 会假定输入始终是整数序列。
    • 可接受且快速的答案,但是我的程序将大量使用 { 和 },因此该解决方案会很快崩溃。
    【解决方案2】:

    使用re.sub:

    import re
    
    counter = 0
    
    def replacer(match):
        global counter
        counter += 1
        return str(counter)
    
    re.sub(r'hi', replacer, text)
    

    这将比使用 str.replace 的任何替代方法都要快

    【讨论】:

      【解决方案3】:

      re.sub 的一个解决方案:

      text = 'fhihihi'
      lst = [1,2,3]
      
      import re
      print(re.sub(r'hi', lambda g, l=iter(lst): str(next(l)), text))
      

      打印:

      f123
      

      【讨论】:

        【解决方案4】:

        其他答案给出了很好的解决方案。如果你想重新发明轮子,这里有一种方法。

        text = "fhihihi"
        target = "hi"
        
        l = len(target)
        i = 0
        c = 0
        new_string_list = []
        while i < len(text):
            if text[i:i + l] == target:
                new_string_list.append(str(c))
                i += l
                c += 1
                continue
            new_string_list.append(text[i])
            i += 1
        
        print("".join(new_string_list))
        

        使用列表来防止连续创建字符串。

        【讨论】:

          猜你喜欢
          • 2017-06-22
          • 2019-06-26
          • 2023-01-30
          • 2021-05-22
          • 1970-01-01
          • 2018-06-02
          • 1970-01-01
          • 2013-05-01
          • 1970-01-01
          相关资源
          最近更新 更多