educative.io

Educative

Whats The Difference Between Just Using Print And %s or %i or %f

As The Title specifies is there a real difference between using print than all these other things? And even with the other things I experimented if I could do something like
Testing= “%s+%s=%s” % (4.6,5.9,10.5) #don’t really care if math is correct and also bad name ik
And It Came Out as i wanted so I don’t understand when I would use this or rather
What is the point?


Course: Learn Python 3 from Scratch - Free Interactive Course
Lesson: String Formatting - Learn Python 3 from Scratch

hi @Kosee,

Thank you so much for reaching out to us. Python support output formatting and that can be done using %. We have different format specifiers

  1. For integers, we have %i
  2. For strings, we have %s
  3. For floating-point values, we have %f
  4. For the decimal number system, we have %d
  5. For the octal number system, we have %o
  6. For the hexadecimal number system, we have %x

If you want to print simple information like following

name = "Kosee"
number_of_posts = 1

We can use either print("%s have posted %i post(s)" % (name, number_of_posts)) or print(name, "have posted", number_of_posts, "post(s)") both will give us the same output.

In the first one, we can see that we are not using " again and again as we did for the second one. It is always our choice to pick the one we like or feels comfortable working with (no pressure).

But if we need to show some conversions, then the output formator might come in handy. For example, we want to show the octal and hex values of a decimal number. We can only write single line instruction print("Octal value of 20 is %o and hex value of 20 is %x" %(20, 20))

I hope I have answered your question but if there seems anything missing then please do let me know. Thanks.