In this post, let's take a quick look at the format()
method in Python.
What is .format()
?
.format()
is a special function in Python that is used with print()
to customize the output format easily.
Example
Consider the below code,
a = 10
b = 20
c = 30
We want to print the output like below,
10 + 20 - 30 = 0
Generally we would do something like below,
print(a,"+",b,"-",c,"=",a+b-c)
This works fine! but it's boring and looks more complex than a Christopher Nolan film. This is not Python known for!
Lets do it in Python way 😎
Here comes the format()
function.
Using format()
the above can be achieved as below,
Type 1
print("{} + {} - {} = {}".format(a,b,c,a+b-c))
That's it! this looks much better than the original implementation.
Type 2
We can also specify the index position for the format method if you want,
print("{0} + {1} - {2} = {3}".format(a,b,c,a+b-c))
The first argument in the format()
will replace the {0}
and the second argument in format()
will replace {1}
and so on.
Type 3
We can also use keywords instead of index.
print("{0} + {1} - {2} = {res}".format(a,b,c, res = a+b-c))
Here, the res
will be replaced by its definition.
That's it devs. Follow for more awesome tutorials ❤