TypeError:无法连接'str'和'int'对象

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).


car*_*sdc 8

你需要加括号: (y+z)

  • 如果不是python认为你正在做("无论如何%d"%y)+ z (5认同)
  • `%`的优先级低于`+`,因此`a%b + c`被解析为`(a%b)+ c`,而你想要的是'a%(b + c)` (3认同)