Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Replacement with Array of Strings

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!

like image 798
Michael Avatar asked Jan 23 '26 22:01

Michael


2 Answers

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'
like image 116
Ashwini Chaudhary Avatar answered Jan 25 '26 10:01

Ashwini Chaudhary


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}'
like image 27
Martijn Pieters Avatar answered Jan 25 '26 12:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!