How to use a dictionary for string formatting In Python
Using a dictionary to unpack values into the placeholders in the string that needs to be formatted. We basically use ** to unpack the values. This method can be useful in string substitution while preparing an SQL query.
Python3
introduction = 'My name is {first_name} {middle_name} {last_name} AKA the {aka}.' full_name = { 'first_name' : 'Tony' , 'middle_name' : 'Howard' , 'last_name' : 'Stark' , 'aka' : 'Iron Man' , } # Notice the use of "**" operator to unpack the values. print (introduction. format ( * * full_name)) |
Output:
My name is Tony Howard Stark AKA the Iron Man.
Python String format() Method
The format()
method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex string formatting more efficiently. Sometimes we want to make generalized print statements in that case instead of writing print statements every time we use the concept of formatting.