How can I escape the format string?

前端 未结 3 1011
-上瘾入骨i
-上瘾入骨i 2020-12-19 08:46

Is it possible to use Python\'s str.format(key=value) syntax to replace only certain keys.

Consider this example:

my_string = \'Hello {n         


        
3条回答
  •  暖寄归人
    2020-12-19 09:35

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

提交回复
热议问题