2

What does str.format do? Why should I use it? What's the difference between using

print(a, b)

and

print("{} {}".format(a, b))

Thanks in advance.

OsmanMansurov
  • 77
  • 1
  • 7
  • please read this https://realpython.com/python-f-strings/ – Akhilesh_IN Jul 23 '20 at 15:36
  • In your above example there is really no use for it. But you can do with it alot of special things, like align strings and save yourself the `str()` conversion for numbers just to name a few benefits. Read https://pyformat.info/ to see more benefits – Tomerikoo Jul 23 '20 at 15:57
  • Some more examples from here: https://stackoverflow.com/questions/517355/string-formatting-in-python ; https://stackoverflow.com/questions/13945749/string-formatting-in-python-3 ; https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points – Tomerikoo Jul 23 '20 at 16:02
  • You should use [f-strings: PEP 498 - Literal String Interpolation](https://www.python.org/dev/peps/pep-0498/) because they're easier to read. `print(f'{a} {b}')` – Trenton McKinney Jul 26 '20 at 01:11
  • Very interesting. Thanks! – OsmanMansurov Jul 27 '20 at 15:49

1 Answers1

1

Theformat()method takes the arguments or variables which are passed, formats them, and places them in the string wherever the placeholders{}symbol is used.

a = 5

#single formatting
b = "My name is XYZ & my age is just {}"
print (b.format(a))

#multiple formatting
c = "My name is XYZ & my age is just {}. Also I have a sibling who's age is also {}"
print(c.format(a, a))



Output:

 My name is XYZ & my age is just 5  My name is XYZ & my age is just {}. Also I have a sibling who's age is also 5

  • one more use #multiple formatting with indexing c = "My name is {2} & my age is just {0}. Also I have a sibling who's age is {1}" print(c.format(5, 8, "XYZ")) Output: My name is XYZ & my age is just 5. Also I have a sibling who's age is 8 – Himanshu Bhardwaj Jul 23 '20 at 15:52