DEV Community

loading...
Cover image for .format in Python ⚙

.format in Python ⚙

manitej profile image Manitej ⚡ Originally published at manitej.hashnode.dev ・1 min read

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
Enter fullscreen mode Exit fullscreen mode

We want to print the output like below,

10 + 20 - 30 = 0
Enter fullscreen mode Exit fullscreen mode

Generally we would do something like below,

print(a,"+",b,"-",c,"=",a+b-c)
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

Here, the res will be replaced by its definition.

That's it devs. Follow for more awesome tutorials ❤

Discussion

pic
Editor guide
Collapse
alexc957 profile image
alexc957

good, but there are f-strings and they are better and simpler than calling the format method.

Collapse
andrewbaisden profile image
Andrew Baisden

f-strings are much nicer I agree.