What's the point of {} followed by format and how to use it in python?

I’m having trouble understanding the point of {} since when I see it, it’s used the same way as a print("",variable,""). I’ve only learned about it today and it’s used like this:


Human is a class and place a variable that’s introduced by the class Human

>Solution :


x = 5
str1 = 'hi'
str2 = 'bye'
print(str1, x, str2)
print('{}{}{}'.format(str1, x, str2))

Let’s look at some of the outputs.

>>> print(str1, x, str2)
hi 5 bye

>>> print(f'{str1}{x}{str2}')

>>> print('{}{}{}'.format(str1, x, str2))

We can clearly see that they are not the same. Printing things out using the first method adds a space between each, which may or may not be what we want. Using f-strings or .format allows for better control of your output.

Say I want a tab between str1 and x, but no space between x and str2.

# To do this using your first method:
>>> print(str1, '\t', x, str2, sep='')
hi  5bye

# Versus an f-string:
>>> print(f'{str1}\t{x}{str2}')
hi  5bye

The second would be widely considered to be more clear.

Leave a Reply