The Python String format_map() method is used to is used to perform string formatting with the help of a mapping object, such as a dictionary.
It is similar to the format() method but instead of passing arguments directly, it takes a single mapping object as its argument. This mapping object contains "key-value" pairs where the "keys" correspond to the placeholders in the string, and the "values" represent the replacements for those placeholders.
SyntaxFollowing is the basic syntax of the Python String format_map() method −
string.format_map(mapping)Parameters
This method accepts a mapping object (such as a dictionary) that contains key-value pairs as a parameter.
Return ValueThe method returns a formatted string with the placeholders replaced by their corresponding values from the mapping. It does not modify the original string.
Example 1In the following example, we are formatting a string using a dictionary person with keys 'name' and 'age'. The format_map() method replaces placeholders "{name}" and "{age}" with the corresponding values from the dictionary −
person = {'name': 'Alice', 'age': 25} result = "Name: {name}, Age: {age}".format_map(person) print(result)Output
The output obtained is as follows −
Name: Alice, Age: 25Example 2
Here, we access nested values in the dictionary "student". The format_map() method replaces placeholders "{details[name]}" and "{details[age]}" with the corresponding nested values −
student = {'details': {'name': 'Bob', 'age': 20}} result = "Name: {details[name]}, Age: {details[age]}".format_map(student) print(result)Output
Following is the output of the above code −
Name: Bob, Age: 20Example 3
In this example, we format a string using attributes of an object "person" dynamically. The vars() function converts the object's attributes into a dictionary, which is then used by format_map() method to replace placeholders −
class Person: pass person = Person() person.name = 'John' person.age = 30 result = "Name: {name}, Age: {age}".format_map(vars(person)) print(result)Output
The result produced is as shown below −
Name: John, Age: 30Example 4
In here, we define a custom dictionary class "CustomDict" where missing keys are handled by the __missing__() method. If a key is missing in the dictionary data, it returns a custom string instead of raising a KeyError −
class CustomDict(dict): def __missing__(self, key): return f'Unknown: {key}' data = CustomDict({'name': 'Alice'}) result = "Name: {name}, Age: {age}".format_map(data) print(result)Output
We get the output as shown below −
Name: Alice, Age: Unknown: age
python_string_methods.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4