Friday, October 3, 2025
HomeLanguagesHow to format a string using a dictionary in Python

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": "Lazyroar",
         "Department": "Computer Science"}
 
# Calling the .format() function
# over the above given value
print("{Company} is a {Department} Portal.".format(**value))


Output:

Lazyroar 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": "Lazyroar",
         "Department": "Computer Science"}
   
# Using f-strings
print(f"{value['Company']} is a {value['Department']} Portal.")
#This code is contributed by Edula Vinay Kumar Reddy


Output

Lazyroar is a Computer Science Portal.
RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11868 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11929 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7080 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS