How to format a string using a dictionary in Python
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
# Python program to illustrate the # formatting of a string using a dictionary # Initializing a value value = { "Company" : "GeeksforGeeks" , "Department" : "Computer Science" } # Calling the .format() function # over the above given value print ( "{Company} is a {Department} Portal." . format ( * * value)) |
Output:
GeeksforGeeks is a Computer Science Portal.
Method 2: Using % operator
% – 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
# Python program to illustrate the # formatting of a string using a dictionary # String formatting in dictionary 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
# Python program to illustrate the # formatting of a string using a dictionary # Initializing a value value = { "Company" : "GeeksforGeeks" , "Department" : "Computer Science" } # Using f-strings print (f "{value['Company']} is a {value['Department']} Portal." ) #This code is contributed by Edula Vinay Kumar Reddy |
GeeksforGeeks is a Computer Science Portal.
Please Login to comment...