我在这里没有看到问题,但 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
。
为什么会这样?我没有将任何变量设置为字符串...据我所知。
最佳答案
%
的优先级高于+
,所以s % y + z
被解析为(s % y) + z
.
如果 s
是一个字符串,那么 s % x
也是一个字符串,并且 (s % y) + z
尝试添加一个字符串(s % y
的结果)和一个整数(z
的值)。
关于python - "TypeError: cannot concatenate ' str ' and ' int ' objects"尝试使用 printf 样式格式时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7001664/