Explicit String Conversion


#1

Must I convert a number to a string; print "The value of pi is around " + str(3.14), while I can as well write this; print “The value of pi is around 3.14” ? I don’t see the essence


#2

Conversion is necessary to permit concatenating.

>>> number = 42
>>> "string " + number

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    "string " + number
TypeError: cannot concatenate 'str' and 'int' objects
>>> "string " + str(number)
'string 42'
>>> from math import pi
>>> "The value of pi is " + str(pi)
'The value of pi is 3.14159265359'
>>> 

#3

But both of them have the same output :thinking::thinking:


#4

That’s because of the literal expression. Notice the example above uses a math constant.


#5

Oh, okay, I now get it , Thank you.