Replacing a string with an array of strings

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 with the corresponding 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?

Thank!

+3
source share
4 answers

Use str.replaceand replace '?'with '{}', then you can just use the method str.format:

>>> s = "?, ?, ?, test4, test5"
>>> replace_array = ['test1', 'test2', 'test3']
>>> s.replace('?', '{}', len(replace_array)).format(*replace_array)
'test1, test2, test3, test4, test5'
+5
source

Use str.replace()with 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 line does not contain curly braces, you can also replace 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'

{ }, :

s = s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)

:

>>> s = "{?, ?, ?, test4, test5}"
>>> s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
'{test1, test2, test3, test4, test5}'
+4

And a regular expression with a functional approach that scans a string only once, is more flexible in terms of adapting a replacement pattern, does not conflict with existing formatting operations and can be changed to provide default values ​​if there are not enough replacements ...:

import re

s = "?, ?, ?, test4, test5"
replace_array = ['test1', 'test2', 'test3']
res = re.sub('\?', lambda m, rep=iter(replace_array): next(rep), s)
#test1, test2, test3, test4, test5
+2
source

Try the following:

s.replace('?', '{}').format(*replace_array)
=> 'test1, test2, test3, test4, test5'

Even better, if you substitute the characters ?with {}placeholders, you can directly call format()without calling first replace(). After that, he format()takes care of everything.

+1
source

All Articles