Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

print("planet:{}".format(Human.place))

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Given:

x = 5
str1 = 'hi'
str2 = 'bye'
print(str1, x, str2)
print(f'{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}')
hi5bye

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

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading