Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between str.format_map(mapping) and str.format

I don't understand the str.format_map(mapping) method. I only know it is similar to str.format(*args, **kwargs) method and you can also pass a dictionary as an argument (please see my example). Example:

print ("Test: argument1={arg1} and argument2={arg2}".format_map({'arg1':"Hello",'arg2':123}))

Can someone explain to me the difference between str.format_map(mapping) and str.format(*args, **kwargs) methods and why do I need the str.format_map(mapping) method?

like image 841
N Randhawa Avatar asked Apr 21 '16 21:04

N Randhawa


People also ask

What is the difference between format () and Format_map in Python?

The difference can be summarized below: The format() method indirectly performs a substitution using the parameters of the method, by creating a mapping dictionary first, and then performing the substitution. In the case of Python String format_map(), the substitution is done using a mapping dictionary, directly.

What does str format do?

Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

What is the use of Format_map in Python?

Python String format_map() method is an inbuilt function in Python, which is used to return a dictionary key's value. Parameters: Here z is a variable in which the input dictionary is stored and string is the key of the input dictionary. input_dict: Takes a single parameter which is the input dictionary.


2 Answers

str.format(**kwargs) makes a new dictionary in the process of calling. str.format_map(kwargs) does not. In addition to being slightly faster, str.format_map() allows you to use a dict subclass (or other object that implements mapping) with special behavior, such as gracefully handling missing keys. This special behavior would be lost otherwise when the items were copied to a new dictionary.

See: https://docs.python.org/3/library/stdtypes.html#str.format_map

like image 169
kindall Avatar answered Sep 19 '22 08:09

kindall


str.format(**mapping) when called creates a new dictionary, whereas str.format_map(mapping) doesn't. The format_map(mapping) lets you pass missing keys. This is useful when working per se with the dict subclass.

class Foo(dict): # inheriting the dict class
    def __missing__(self,key):
        return key
print('({x},{y})'.format_map(Foo(x='2')))  # missing key y 
print('({x},{y})'.format_map(Foo(y='3')))  # missing key x
like image 30
kevin Avatar answered Sep 20 '22 08:09

kevin