Understanding the format method in Python
In this post, we will take a look at Python's format() method.
What is the format used for?
The format() method in Python is used to format the output.
Example
Consider, we want to print the below statement as our output.
10 + 20 - 30 = 0
Generally we will do it the below way,
a = 10
b = 20
c = 30
print(a," + ",b," - ",c," = ",a+b-c)
As you can see above the statement we used looks very complex and boring.
To format in a better way, we can use the format() method in Python as below.
a = 10
b = 20
c = 30
print("{} + {} - {} = {}".format(a,b,c,a+b-c))
The statement looks way more cleaner and less complex.
We can also indicate the empty braces with a number or character.
a = 10
b = 20
c = 30
print("{0} + {1} - {2} = { res}".format(a,b,c,res = a+b-c))
Check Output Here
The number inside the braces indicates the format method's argument index, which means the first argument in format() function will replace the {0} and the second argument will replace the {1} and so on. Similarly, the {res} will be replaced by the res value.