Computer >> Computer tutorials >  >> Programming >> Python

Python format() function


The format() method formats some specified value and insert them inside the string's placeholder.The placeholder is presented by {}. In this article we will see various ways the format function can be used.

Single format()

In this example take numbers in a given range substitute them in a place holder with a fixed string.

Example

for i in range(19,25):
   print("There are {} boxes!".format(i))

Output

Running the above code gives us the following result −

There are 19 boxes!
There are 20 boxes!
There are 21 boxes!
There are 22 boxes!
There are 23 boxes!
There are 24 boxes!

Multiple format()

In this sample we use multiple parameters so this can be used with multiple place holders.

Example

i=1
months={'Jan','Feb','Mar'}
for m in months:
   print("Month no {} is {}".format(i,m))
   i=i+1

Output

Running the above code gives us the following result −

Month no 1 is Jan
Month no 2 is Mar
Month no 3 is Feb

Using positional index

Specific place holders can be filled with the specific positions of the parameters in the format string.

Example

print("This week I'm workigm on {1},{2} and {4}".format('Mon','Tue','Wed','Thu','Fri'))

Output

Running the above code gives us the following result −

This week I'm workigm on Tue,Wed and Fri

Using Keywords

We can also use keywords along with symbols which can be placed in the containers.

Example

print("The 3{r}, 4{t} and 5{t} ranks are winners".format(r='rd',t='th'))

Output

Running the above code gives us the following result −

The 3rd, 4th and 5th ranks are winners