python - 将子字符串的多个实例替换为列表中的项目

标签 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"

最佳答案

您可以使用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

关于python - 将子字符串的多个实例替换为列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53874578/

相关文章:

java - stringBuilder.reverse 如何工作?

python - 查找进程是否在 Windows psutil 中运行

python opencv2 findHomography

python - 在 scikit learn 中组合随机森林模型

php - 如何使用 PHP + 大数据库将数据从 MySQL 转换为 JSON

php - 将元素添加到具有间隙数字键的数组以形成索引数组/列表

java - 如何将一维数组分解为行?

python - 从 pandas 数据框中的字符串中提取信息非常困难

python - 创建一个热标签,一个基于多种条件的热编码

c - 从 C 文本文件中读取字符串并确定行尾