TypeError:无法连接'str'和'int'对象 [英] TypeError: cannot concatenate 'str' and 'int' objects
问题描述
我现在正在学习Python,是的!无论如何,我有小问题。我在这里看不到问题:
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
但Python认为不同 - TypeError:无法连接'str'和'int'对象
。
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.
推荐答案
%
的优先级高于 +
,因此 s%y + z
被解析为(s%y)+ z
。
%
has a higher precedence than +
, so s % y + z
is parsed as (s % y) + z
.
如果 s
是一个字符串,然后 s%x
是一个字符串,(s%y)+ z
尝试添加一个字符串string( 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
).
这篇关于TypeError:无法连接'str'和'int'对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!