Skip to content
Related Articles

Related Articles

How to format a string using a dictionary in Python

Improve Article
Save Article
  • Last Updated : 31 Aug, 2021
Improve Article
Save Article

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.
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!