用列表中的项目替换子字符串的多个实例

时间:2018-12-20 19:04:32

标签: python arrays string list replace

我有一个如下所示的字符串:

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'中的项目,最后使用join函数来获取所需的输出。

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"

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)