使用字符串数组替换字符串

Mic*_*ael 3 python string replace list

假设我有一个字符串s

s = "?, ?, ?, test4, test5"
Run Code Online (Sandbox Code Playgroud)

我知道有三个问号,我想用下面的数组相应地替换每个问号

replace_array = ['test1', 'test2', 'test3']
Run Code Online (Sandbox Code Playgroud)

获得

output = "test1, test2, test3, test4, test5"
Run Code Online (Sandbox Code Playgroud)

Python中是否有一个函数,类似的东西s.magic_replace_func(*replace_array)会实现预期的目标?

谢谢!

Ash*_*ary 5

使用str.replace和更换'?''{}',那么你可以简单的使用str.format方法:

>>> s = "?, ?, ?, test4, test5"
>>> replace_array = ['test1', 'test2', 'test3']
>>> s.replace('?', '{}', len(replace_array)).format(*replace_array)
'test1, test2, test3, test4, test5'
Run Code Online (Sandbox Code Playgroud)