How can I avoid the format string?

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

Consider the following example:

 my_string = 'Hello {name}, my name is {my_name}!' my_string = my_string.format(name='minerz029') 

which returns

 KeyError: 'my_name' 

Is there any way to achieve this?

+6
source share
3 answers

A slightly simpler workaround that 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 easily be expanded with more keys in the to_replace dict and will not complain even if the search string does not exist. It could probably be improved to offer more .format() functions, but that was enough for me.

0
source

You can escape my_name using double curly braces, e.g.

 >>> 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, the external {} is deleted once and {{my_name}} becomes {my_name} . If you later want to format my_name , you can just format it again, for example

 >>> 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!' 
+14
source

Python3.2 + has a format_map that allows you to 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 there is no need to add additional {} , only the keys that you point to D will be replaced

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

 my_string.format(**D(name='minerz029')) 
+6
source

Source: https://habr.com/ru/post/956916/


All Articles