Python String format_map()

Python String format_map() method returns a new string value that is formatted using the placeholders in given string and the mapping passed as argument to the format_map() method.

In this tutorial, we will learn the syntax and examples for format_map() method of String class.

Syntax

The syntax of String format_map() method in Python is

str.format_map(**map)

where

ParameterRequired/OptionalDescription
**mapRequiredA dictionary.
ADVERTISEMENT

Example

In this example, we will take a string, and format this string with a dictionary passed to the format_map() method.

Python Program

x = 'Hello {name}! Welcome to {country}. '
result = x.format_map({'name': 'XYZ', 'country': 'New World'})
print(result)
Try Online

Output

Hello XYZ! Welcome to New World.

Explanation

{key}s in the string x are placeholders. Positional arguments are loaded into these placeholders based on the key.

Conclusion

In this Python Tutorial, we learned how to format a given string with placeholders using String method – format_map().