Skip to content
Related Articles

Related Articles

Improve Article

How to format a string using a dictionary in Python

  • Last Updated : 31 Aug, 2021

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :