使用printf风格格式化时出现"TypeError: 无法连接'str'和'int'对象
我在这里看不出有什么问题,但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
我遇到了一个错误,提示是 TypeError: cannot concatenate 'str' and 'int' objects
。
这是为什么呢?我没有把任何变量设置为字符串……至少从我看到的情况来看是这样的。
2 个回答
8
你需要加上括号:(y+z)
13
%
的优先级比 +
高,所以 s % y + z
会被理解为 (s % y) + z
。
如果 s
是一个字符串,那么 s % x
的结果也是一个字符串,而 (s % y) + z
则试图把一个字符串(s % y
的结果)和一个整数(z
的值)相加。