【问题标题】:Replace multiple instances of a sub-string with items in a list用列表中的项目替换子字符串的多个实例
【发布时间】:2019-05-21 07:45:56
【问题描述】:

我有一个如下字符串:

e = "how are you how do you how are they how"

我的预期输出是:

out = "how1 are you how2 do you how3 are they how4"

我正在尝试以下方式:

def givs(y,x):
    tt = []
    va = [i+1 for i in list(range(y.count(x)))]
    for i in va:
        tt.append(x+str(i))
    return tt

ls = givs(e, 'how')

ls = ['how1', 'how2', 'how3', 'how4']

fg = []
for i in e.split(' '):
    fg.append(i)

fg = ['how', 'are', 'you', 'how', 'do', 'you', 'how', 'are', 'they', 'how']

对于 'fg' 中的每个 'how' 实例,我想用 'ls' 中的项目替换,最后使用连接函数来获得所需的输出。

expected_output = ['how1', 'are', 'you', 'how2', 'do', 'you', 'how3', 'are', 
                  'they', 'how4']

以便我可以通过以下方式加入项目:

' '.join(expected_output)

得到:

out = "how1 are you how2 do you how3 are they how4"

【问题讨论】:

    标签: python arrays string list replace


    【解决方案1】:

    无需让您的代码复杂化,只需添加一个计数器并将其添加到每个“方法”中即可。最后制作新字符串。

    e = "how are you how do you how are they how"
    e_ok = ""
    count = 1
    for i in e.split():
        if i == "how":
            i = i+str(count)
            count += 1
        e_ok += i + " "
    print(e_ok)
    

    【讨论】:

    • 欢迎来到 Stack Overflow。谢谢您的回答。虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。 How to Answer。问候。
    【解决方案2】:

    你可以使用itertools.count:

    from itertools import count
    
    counter = count(1)
    
    e = "how are you how do you how are they how"
    
    result = ' '.join([w if w != "how" else w + str(next(counter)) for w in e.split()])
    
    print(result)
    

    输出

    how1 are you how2 do you how3 are they how4
    

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多