-1

I am trying to teach my friend Python and showed him 3 methods of printing variables of different types without the need for converting them to strings first, but he wants to know which one should he use and I don't know as I have not used Python in a long time so hopefully you can help us out:

print("There are %d people in total" % num_people)

or

print("There are", num_people, "people in total")

or

print("There are {} people in total".format(num_people))

I know that the format method can do other, more powerful, string manipulation operations but other then that I am not sure which is the preferred method to use. I don't know why the first method exists as the 2nd seems simpler.

Any thoughts on this? Thank you!

Mayron
  • 2,146
  • 4
  • 25
  • 51

2 Answers2

2

The Python style guide recommends using the format method. Here is the link to that document: "PEP 3101"

I_am_Grand
  • 96
  • 6
1

With regards to % vs. .format please see similar questions like this, as others have pointed out.

Regarding

print("There are", num_people, "people in total")

This is really just a convenience provided by the print() function. In stead of printing just one argument, the signature allows for multiple arguments, which are converted to string separately and then joined with one blank (by default) as a separator. This is quite useful for a quick output of several objects, but generally unsuited for generating formatted output. Just printing a decimal number that is given with high precision may produced an output of limited usability. See the documentation of print() for more information on its capabilities.

Community
  • 1
  • 1
PeterE
  • 5,715
  • 5
  • 29
  • 51
  • Thank you, I was mainly concerned with the difference between printing with multiple arguments and formatting so this helped. – Mayron Jul 12 '16 at 10:56