Why you would use the "str()" command?


#1

Hello, I am new to learning Python, and right away it seemed like the str() command is useless. As far as I understand it turns a variable into a string so that you can successfully combine a string and a variable when using the print command. If this is true, then why would you not simply put:

print 'The value of pi is approximately equal to ’ + ‘3.14’ instead of print … + str(3.14)

also why could you not just change it to: print ‘The value of pi is approximately equal to 3.14’

Basically I am asking why you would ever use this command and why you would combine strings with a + when you could just write it all in one string.

Thanks for any responses!

Strings and Console Output


#2

Care to reconsider that statement?

>>> "1" * 3
'111'
>>> 3 * "1"
'111'
>>> "1" + 3
Traceback (most recent call last):
  File "<pyshell#137>", line 1, in <module>
    "1" + 3
TypeError: Cannot convert 'int' object to 'str' implicitly
>>> 3 + "1"
Traceback (most recent call last):
  File "<pyshell#138>", line 1, in <module>
    3 + "1"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> str(3) + "1"
'31'
>>> "1" + str(3)
'13'
>>> 

#3

Oh ok I think I see it now, so “1+3” is 4 but “1” + str(3) is 13. I think it makes more sense now.


#5

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