How can I escape the format string?

喜夏-厌秋 提交于 2019-11-28 03:54:36

问题


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?


回答1:


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!'



回答2:


Python3.2+ has format_map which lets you do this

>>> class D(dict):
...     def __missing__(self, k):return '{'+k+'}'
... 
>>> my_string = 'Hello {name}, my name is {my_name}!'
>>> my_string.format_map(D(name='minerz029'))
'Hello minerz029, my name is {my_name}!'
>>> _.format_map(D(my_name='minerz029'))
'Hello minerz029, my name is minerz029!'

Now it's not necessary to add extra {}, only the keys you provide to D will be substituted

As @steveha points out, if you are on an older Python3 you can still use

my_string.format(**D(name='minerz029'))



回答3:


A bit of a simpler workaround which I use:

my_string = 'Hello {name}, my name is {my_name}!'

to_replace = {
    "search_for" : "replace_with",
    "name" : "minerz029",
}

for search_str in to_replace:
    my_string = my_string.replace('{' + search_str + '}', to_replace[search_str])

print(my_string)

This can be expanded easily with more keys in the to_replace dict and wont complain even if the search string doesn't exist. It could probably be improved to offer more of .format()'s features, but it was enough for me.



来源:https://stackoverflow.com/questions/19649427/how-can-i-escape-the-format-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!