用列表元素替换文件中的每个出现 - 每个下一个出现的列表下一个元素
Replace every occurence in a file with a list elements - every next occurence with a list's next element
假设,我需要替换文件中的每个 's',前提是我知道其中有三个,并在每个列表元素出现的基础上替换每个出现:
This is my test
列表:[1, 2, 3]
替换后的期望输出:
Thi1 i2 my te3t
最elegant/pythonic的方法是什么?
您可以将 s
s 替换为占位符并使用 str.format
来填充:
s = "This is my test".replace('s','{}')
lst = [1, 2, 3]
out = s.format(*lst)
输出:
'Thi1 i2 my te3t'
假设,我需要替换文件中的每个 's',前提是我知道其中有三个,并在每个列表元素出现的基础上替换每个出现:
This is my test
列表:[1, 2, 3]
替换后的期望输出:
Thi1 i2 my te3t
最elegant/pythonic的方法是什么?
您可以将 s
s 替换为占位符并使用 str.format
来填充:
s = "This is my test".replace('s','{}')
lst = [1, 2, 3]
out = s.format(*lst)
输出:
'Thi1 i2 my te3t'