简体   繁体   English

如何转义格式字符串?

[英]How can I escape the format string?

Is it possible to use Python's str.format(key=value) syntax to replace only certain keys. 是否可以使用Python的str.format(key=value)语法仅替换某些键。

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_name进行转义,如下所示

>>> 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} . 如您所见,格式化一次后,外面的{}被删除, {{my_name}}变成{my_name} If you later want to format my_name , you can simply format it again, like this 如果以后要格式化my_name ,则只需再次格式化它,就像这样

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

Python3.2+ has format_map which lets you do this Python3.2 +具有format_map ,可让您执行此操作

>>> 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 现在不必添加额外的{} ,只需替换您提供给D的键

As @steveha points out, if you are on an older Python3 you can still use 正如@steveha指出的那样,如果您使用的是较旧的Python3,则仍然可以使用

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

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. 可以使用to_replace字典中的更多键轻松扩展此功能,即使搜索字符串不存在也不会抱怨。 It could probably be improved to offer more of .format() 's features, but it was enough for me. 可能可以进行改进以提供更多.format()的功能,但这对我来说已经足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM