Is it possible to use Python's str.format(key=value)
syntax to replace only certain keys.
Consider this example:
my_string = 'Hello {name}, my name is {my_name}!'
my_string = my_string.format(name='minerz029')
which returns
KeyError: 'my_name'
Is there a way to achieve this?
You can escape my_name
using double curly brackets, like this
>>> my_string = 'Hello {name}, my name is {{my_name}}!'
>>> my_string.format(name='minerz029')
'Hello minerz029, my name is {my_name}!'
As you can see, after formatting once, the outer {}
is removed and {{my_name}}
becomes {my_name}
. If you later want to format my_name
, you can simply format it again, like this
>>> my_string = 'Hello {name}, my name is {{my_name}}!'
>>> my_string = my_string.format(name='minerz029')
>>> my_string
'Hello minerz029, my name is {my_name}!'
>>> my_string.format(my_name='minerz029')
'Hello minerz029, my name is minerz029!'
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