Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I escape the format string?

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?

like image 361
kiri Avatar asked Oct 29 '13 04:10

kiri


1 Answers

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!'
like image 137
thefourtheye Avatar answered Oct 01 '22 03:10

thefourtheye