daG*_*vis 4 python string integer concatenation typeerror
我现在正在学习Python,耶!无论如何,我有小问题.我在这里看不到问题:
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
Run Code Online (Sandbox Code Playgroud)
但Python认为不同 - TypeError: cannot concatenate 'str' and 'int' objects.
为什么会这样?我没有像字符串那样设置任何变量......就像我看到的那样.
MRA*_*RAB 13
%优先级高于+,因此s % y + z解析为(s % y) + z.
如果s是字符串,则s % x是字符串,并(s % y) + z尝试添加字符串(结果s % y)和整数(值z).
你需要加括号: (y+z)