根据教程要点:
The method replace() returns a copy of the string in which the occurrences of old have been replaced with 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'
最佳答案
您可以创建 format string在你的初始字符串之外:
>>> text = 'fhihihi'
>>> replacement = [1,2,3]
>>> text.replace('hi', '{}').format(*replacement)
'f123'
关于python - 根据列表替换字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56779248/