A one-line solution:
string.replace('@@@', '{}', len(kv)).format(*kv.values())
Short explanation:
- Replace all
'@@@' strings with the python string formatting identifier '{}'. len(kv) reduces the number of replaces to the length of the dict, avoiding IndexError when the dict has less elements than the number of '@@@' in the string
- extract dictionary values with
kv.values()
- unpack dictionary values with
*kv.values() and pass this as argument to the string format method.
Sample code execution:
Input
string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {'1': 'hi', '2': 'there', '3': 'bla'}
And output
string.replace('@@@', '{}', len(kv)).format(*kv.values())
#Out: 'asfd hi fdsfd there ffds bla asdf'
Advantage of this solution:
No explicit looping (explicit looping is almost always a bad idea in python) and only one line of code. Furthermore this is also working when the number of '@@@' is less **or greater than the number of values in kv**, when the count parameter in str.replace is specified.
This leads to the final and 99% failsafe variant of my solution, using the len of the dict as count argument in replace:
string.replace('@@@', '{}', len(kv)).format(*kv.values())