Format() Method Of Str Class

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:

# 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:

City x City y City z

Welcome Alice

 


Copyright 2023 © pythontic.com