Why do I need str() to print a number?


#1

I’m on “Explicit String Conversion” in “Learn Python”. It wants me to convert 3.14 to a string by using str(3.14), but I’m wondering why I can’t just write “3.14”.

Thank you,


#2

But what if you retrieve an integer value from database? then you can’ just write it

sometimes, codecademy teaches a concept which you need to know, and is very useful later


#3

Part of explicit string conversion deals with changing the type to match its usage. Output is generally given as text, when it reaches the screen or page. By converting non-string data points to str we allow for one contiguous string object which is much simpler to parse for output, and to store as a single object.

>>> from math import pi
>>> print (type(round(pi, 2)))
<class 'float'>
>>> print (str(round(pi, 2)))
3.14
>>> _pi = str(round(pi, 2))
>>> _pi
'3.14'
>>> pi_str = "The most common short form for PI is, " + _pi + "."
>>> pi_str
'The most common short form for PI is, 3.14.'
>>> pi_str = "The most common short form for PI is, %s." % _pi
>>> pi_str
'The most common short form for PI is, 3.14.'
>>> 

On a side note, something we cannot do with numbers is split them up. A number is immutable. However, converted to a string we can split it into a list and access/modify each digit at will. Then convert back to a string and then back to a number.


#4

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