Search code examples
pythonstringpython-3.xstring-formatting

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?


Solution

  • 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