Home »
Python
Python String format() Method
By IncludeHelp Last updated : December 15, 2024
Python String format() Method
The format() method is used to format the string (in other words - we can say to achieve the functionality like printf() in C language).
When we need to display the values of the variables inside the string, we can format it by placing {} where we want to place the value. {} is a replacement field, that replaces with the given value in format() method.
The field {} contains the index to replace, the value specified in the format function.
Let suppose, there are three values specified in the format method, {0} for the first value, {1} for the second value and {2} for the third value and so on will be used.
Syntax
String.format(parameter1, parameter2,...)
Parameters
Here, parameter1, parameter2, ... are the values/variables that will print within the string by replacing the field {N}. Where N is the index of the parameter.
Sample Input/Output
print "{0}, {1} and {2}".format("ABC", "PQR", "XYZ")
This statement will print "ABC, PQR, and XYZ"
Example 1: Printing name, age in different output formats
# printing name
print("My name is {0}".format("Amit"))
# printing name and age
print("My name is {0}, I am {1} years old".format("Amit", 21))
# printing name and age through variables
name = "Amit"
age = 21
print("My name is {0}, I am {1} years old".format(name, age))
Output
My name is Amit
My name is Amit, I am 21 years old
My name is Amit, I am 21 years old
Example 2: Calculating SUM, AVERAGE, and printing in different output formats
a = 10
b = 20
sum = a + b
# output 1
print("sum = {0}".format(sum))
# output 2
print("Sum of {0} and {1} is = {2}".format(a, b, sum))
# finding average and printing
a = 11
b = 20
sub = a + b
print("Average of {0} and {1} is = {2}".format(a, b, float(sum) / 2))
Output
sum = 30
Sum of 10 and 20 is = 30
Average of 11 and 20 is = 15.0