python - 根据列表替换字符串中的子字符串

标签 python list replace

根据教程要点:

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/

相关文章:

c# - 我可以在 Python3 中使用不同的代码点吗?

Python:更改嵌套列表的值

c# - 比较 2 个列表的值 C#

java - 如何在Java中用三重正斜杠替换正斜杠?

string - 从字符串中删除空字符

python - 如何为我的 networkx 图指定精确的输出大小?

python - 如何从Python中的多个线程收集数据?

python - 在 Python 线程中使用 Intvar/DoubleVar 是否安全?

python - 根据可能值列表计算列表中的元素

ruby - 有没有一种有效的方法可以在 Ruby 中执行数百个文本替换?