python - "TypeError: cannot concatenate ' str ' and ' int ' objects"尝试使用 printf 样式格式时

标签 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

我收到 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/

相关文章:

python - 我如何使用类别中值进行 df.fillna

python - 使用 GetIndex() 函数

python - 将字符串拆分为整数时出现类型错误

c - 计算基数 4 中匹配数字数量的最快方法是什么?

python - 无法找到或加载 Qt 平台插件 "xcb"

python - werkzeug + django + Gunicorn : TypeError

string - 带有变量的 NSLocalizedString 对我不起作用

c++ - 尝试在 C 中打印字符串变量时出现编译器错误

c++ - 如何在 C/C++ 中检查字符串中的模式?

linux - 如何在bash中用另一个整数变量来增加一个整数变量?