If the placeholders (not "delimiters") were {}
rather than ?
, this would be exactly how the built-in .format
method handles empty {}
(along with a lot more power). So, we can simply replace the placeholders first, and then use that functionality:
>>> s = "I ? am ? a ? string"
>>> l = ['1', '2', '3']
>>> s.replace('?', '{}').format(*l)
'I 1 am 2 a 3 string'
Notice that .format
expects each value as a separate argument, so we use *
to unpack the list.
If the original string contains {
or }
which must be preserved, we can first escape them by doubling them up:
>>> s = "I ? {am} ? a ? string"
>>> l = ['1', '2', '3']
>>> s.replace('?', '{}').format(*l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'am'
>>> s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*l)
'I 1 {am} 2 a 3 string'