我认为这里没有问题,但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
的错误提示。
为什么会出现这种情况呢?我没有将任何变量设置为字符串…至少我没有看到。
str.format()
函数进行字符串格式化。例如:"Anyway, 2nd and 3rd variables sum is {0}. :)".format(y+z)
(在 Python 2.7+中可以省略0
,此时占位符为{}
)。 - JAB