Let's say I have a string s
s = "?, ?, ?, test4, test5"
I know that there are three question marks, and I want to replace each question mark accordingly with the following array
replace_array = ['test1', 'test2', 'test3']
to obtain
output = "test1, test2, test3, test4, test5"
is there a function in Python, something like s.magic_replace_func(*replace_array) that will achieve the desired goal?
Thanks!
Use str.replace and replace '?' with '{}', then you can simply use the str.format method:
>>> s = "?, ?, ?, test4, test5"
>>> replace_array = ['test1', 'test2', 'test3']
>>> s.replace('?', '{}', len(replace_array)).format(*replace_array)
'test1, test2, test3, test4, test5'
Use str.replace() with a limit, and loop:
for word in replace_array:
s = s.replace('?', word, 1)
Demo:
>>> s = "?, ?, ?, test4, test5"
>>> replace_array = ['test1', 'test2', 'test3']
>>> for word in replace_array:
... s = s.replace('?', word, 1)
...
>>> s
'test1, test2, test3, test4, test5'
If your input string doesn't contain any curly braces, you could also replace the curly question marks with {} placeholders and use str.format():
s = s.replace('?', '{}').format(*replace_array)
Demo:
>>> s = "?, ?, ?, test4, test5"
>>> s.replace('?', '{}').format(*replace_array)
'test1, test2, test3, test4, test5'
If your real input text already has { and } characters, you'll need to escape those first:
s = s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
Demo:
>>> s = "{?, ?, ?, test4, test5}"
>>> s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
'{test1, test2, test3, test4, test5}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With