How to format a string using a dictionary in Python
Last Updated :
14 Feb, 2023
In this article, we will discuss how to format a string using a dictionary in Python.
Method 1: By using str.format() function
The str.format() function is used to format a specified string using a dictionary.
Syntax: str .format(value)
Parameters: This function accepts a parameter which is illustrated below:
- value: This is the specified value that can be an integer, floating-point numeric constant, string, characters, or even variables.
Return values: This function returns a formatted string using a dictionary.
Example: Formatting a string using a dictionary
Python3
value = { "Company" : "GeeksforGeeks" ,
"Department" : "Computer Science" }
print ( "{Company} is a {Department} Portal." . format ( * * value))
|
Output:
GeeksforGeeks is a Computer Science Portal.
% – Formatting is a feature provided by Python which can be accessed with a % operator. This is similar to printf style function in C. In this approach, a dictionary is used in which you need to provide the key in the parentheses between the % and the conversion character.
Example: Formatting a string using a dictionary
Python3
print ( '%(Company)s is a %(Department)s Portal.'
% { 'Company' : "GFG" , 'Department' : "CS" })
|
Output:
GFG is a CS Portal.
Method 3: By using f-strings
Python 3.6+ has introduced f-strings support in which keys of a dictionary can be used to format a string. In this approach, you need to place the f prefix before the string and place the key of the dictionary inside the curly braces { }.
Python3
value = { "Company" : "GeeksforGeeks" ,
"Department" : "Computer Science" }
print (f "{value['Company']} is a {value['Department']} Portal." )
|
Output
GeeksforGeeks is a Computer Science Portal.
Share your thoughts in the comments
Please Login to comment...