In this tutorial, we’ll learn what Python string format_map() method is and how to properly use it. We’ll go through multiple Python code examples to understand how format_map method works.
Introduction: Python String format_map() Method
This method is used to format the string and returns it.
Syntax of format_map() Method
string.format_map( mapping(dictionary) )
- Python string format_map method takes a single argument( mapping(dictionary) ).
- It returns a string after formatting it.
Example 1: format_map() works with Dictionary
dictValues={'a':345,'b':'Green','cc':'Python Programming'} print('{a} {b} {cc}'.format_map(dictValues)) print('{a} {cc} {b}'.format_map(dictValues)) print('{a} {cc}'.format_map(dictValues)) print('{a}'.format_map(dictValues)) print('{a}{cc}{b}'.format_map(dictValues)) print('{a} {b}'.format_map(dictValues)) print('{b}'.format_map(dictValues)) print('{a}+{b}'.format_map(dictValues)) print('{a}+{b}+{cc}'.format_map(dictValues)) print('{a} {b} {c}'.format_map(dictValues)) // key error as key'c' is not found
Output
345 Green Python Programming 345 Python Programming Green 345 Python Programming 345 345Python ProgrammingGreen 345 Green Green 345+Green 345+Green+Python Programming KeyError: 'c'
This is how Python string format_map method works. You can try it with even more examples to better understand the working of this method.
Click here if you want to learn more about this method.
Example 2: Python String format_map() Method Return Value
dictValues={'a':345,'b':'Green','cc':'Python Programming'} returnedValue="{cc} {a} {b}".format_map(dictValues) print(returnedValue)
Output
Python Programming 345 Green
We can see that Python string format map method returns a string after formatting it.
Conclusion
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string format_map method. I’d be very happy to receive your feedback on this post. Thank you for reading it.