format() method of str class

The format() method dynamically composes a string in Python, through the place holders {} embedded inside a string. The format() also does not require any format specifiers to be provided.

Str Updated 18 Apr 2021 1 min read

Overview

  • Formatting of a string involves dynamically forming a string with portions of the string already defined and portions to be filled dynamically as the program runs. e.g., Welcome User1, Welcome User2 - As the user logs in, the welcome message is dynamically composed.
  • The method format() fills in the place holders specified through {}. The place holders are replaced either through the index of the positional arguments or through the name of keyword arguments passed.
  • The format() method enables a Python programmer to get rid of formatting a string with format specifiers like %d, %s and others.

Example

python
# Example Python program to dynamically compose

            # Python strings using the method format()

# Using index of the positional arguments

            txt         = "City {2} City {1} City {0}";

# z is the 1st argument which will go in the last

            # y is the 2nd argument which will go in the middle

            # x is the 3rd argument which will go in the first

            formatted   = txt.format("z", "y", "x");

            print(formatted);

# Using the name of the keyword arguments

            txt = "Welcome {userName}";

            formatted   = txt.format(userName="Alice");

            print(formatted);

Output

Output
City x City y City z

Welcome Alice