Explicit String Conversion


#1



https://www.codecademy.com/courses/python-beginner-sRXwR/3/2?curriculum_id=4f89dab3d788890003000096


no matter I print "The value of pi is around " + "3.14" or print "The value of pi is around " + str(3.14)
the result is the same
Why we must use str()?
If we are coding other cases, are these two codes the same?


Replace this line with your code. 
print "The value of pi is around " + "3.14"


#2

>>> from math import pi
>>> pi
3.141592653589793
>>>

We would never write numbers in quotes, so that line of code is out.

Above we have a constant in memory, pi, and as we see it is a very precise number; not exact of course for obvious reasons. We will rarely need all those decimal places. We could recite all of the first 100 decimals, but how many of them are really necessary to our math unless it involves Prime numbers or Euler's equation? No answer needed.

Given the value in memory, we can represent it any which way that suits our needs.

>>> print ("The value of PI is around %.2f" % pi)
The value of PI is around 3.14
>>>

The internals of this statement convert the float to a string representation. That is the aim of string output formatting. The key is in telling the expression what type to expect and how to treat it. If we tell it to expect an integer, %d then that is all it will expect. A float would be truncated. That is an inside look at how this syntax works.


#3

Thank you so much! This really clarifies my question. Thank you.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.