TypeError: cannot concatenate 'str' and 'int' objects

扶醉桌前 提交于 2019-12-20 01:06:00

问题


I'm learning Python now, yay! Anyway, I have small problem. I don't see problem in here:

x = 3
y = 7
z = 2

print "I told to the Python, that the first variable is %d!" % x
print "Anyway, 2nd and 3rd variables sum is %d. :)" % y + z

But Python thinks different - TypeError: cannot concatenate 'str' and 'int' objects.

Why is that so? I haven't setted any variable as string... as much as I see.


回答1:


% has a higher precedence than +, so s % y + z is parsed as (s % y) + z.

If s is a string, then s % x is a string, and (s % y) + z attempts to add a string (the result of s % y) and an integer (the value of z).




回答2:


You need to put parenthesis: (y+z)



来源:https://stackoverflow.com/questions/7001664/typeerror-cannot-concatenate-str-and-int-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!