Python Reference ยท String Methods
Python str.format_map() method
Reference for Python str.format_map(): fill a template from a mapping without copying it, and use __missing__ to supply defaults for absent keys.
The str.format_map() method fills the replacement fields of a template using a single mapping, such as a dictionary. It is similar to format(**mapping), with one important difference: the mapping is used directly instead of being copied into a new dictionary of keyword arguments.
That makes format_map() the right tool when you want custom behavior for missing keys. A dict subclass that defines __missing__() can supply a default, so the template does not raise KeyError.
print("{name} is {age}".format_map({"name": "Ada", "age": 36})) # Ada is 36
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.format_map(mapping)
| Name | Description |
|---|---|
mapping |
Any object that supports mapping[key]. Replacement fields look up their names in it. |
Return value: a new str.
Raises: KeyError if a name is missing and the mapping does not handle it; ValueError for a malformed template; TypeError if the argument is not a mapping.
Usage notes
- Only named fields. Empty (
{}) and numbered () fields cannot be satisfied by a mapping and raise an error. Use names. __missing__()works fordictsubclasses because lookups go through the mapping itself. A plaindictdoes not call__missing__(), butcollections.defaultdictdoes through itsdefault_factory. Note that adefaultdictalso inserts the key as it supplies the default.- No copy. The mapping you pass is the one that is consulted, so it can be large, lazy or custom, such as a
ChainMapof settings layers. - Format specs and conversions work exactly as in
format():{price:.2f},{name!r}. - Attribute access is available too (
{user.name}) if the mapping returns objects, so avoid untrusted templates. - Extra keys are ignored. The mapping may hold more entries than the template uses.
- For plain use, prefer f-strings when the values are already local variables.
Related
str.format(),format(),dict,vars()- Lessons: String formatting, Dictionaries