![](/img/trans.png)
[英]Find all instances of a sub-string in a list of strings and return the index of the string where the sub-string is found
[英]Replace multiple instances of a sub-string with items in a list
我有一个如下字符串:
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
没有必要让你的代码变得复杂,只需添加一个计数器并将其添加到每个“如何”。 最后制作新的字符串。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.