Print Formatting in Python

The format function in Python is used in this manner.
1. print(“{0} + {1} = {2}”.format(2,3,2+3 ))
The {}’s  are used as placeholders. Then the given data is fed at the given positions.
Input
print(“{0} + {1} = {2}”.format(2,3,2+3 ))
Output
2 + 3 = 5

Input
print(“{0} + {0} = {1}”.format(2,2+2 ))
Output
2 + 2 = 4

Input
print(“{1} = {0} + {0}”.format(2,2+2 ))
Output
4 = 2 + 2

Specifying width:
Consider the following 2 statements:
print(“{0} X {1} = {2}”.format(9,1,9*1 ))
print(“{0} X {1} = {2}”.format(9,2,9*2 ))

This is manual  field numbering.

Then we can have automatic field numbering and width:
Input
print(“{:04d} X {:04d} = {:04d}”.format(9,1,9*1 ))
print(“{:04d} X {:04d} = {:04d}”.format(9,2,9*2 ))
Output
0009 X 0001 = 0009
0009 X 0002 = 0018
:04d will feed zeroes if data less than 4.
What happens if data size is more than 4.
Input
print(“{:04d} X {:04d} = {:04d}”.format(9,1,9*1 ))
print(“{:04d} X {:04d} = {:04d}”.format(9,2,9*10000 ))
Output
0009 X 0001 = 0009
0009 X 0002 = 90000

The repeat character can be changed:
print(“{:4d} X {:4d} = {:4d}”.format(9,1,9*1 ))
print(“{:4d} X {:4d} = {:4d}”.format(9,2,9*100 ))
This will fill with space.
9 X 1 = 9
9 X 2 = 900

Using variable names:
Input
print(“a={a:4d},b={b:4d}”.format(b=9,a=6))
Output
a= 6,b= 9

Leave a Reply