Python Can';t将整数转换为字符串

Python Can';t将整数转换为字符串,python,Python,我对Python程序的这个问题有点困惑。这是一个非常简单的程序,但它总是出现问题。请允许我向您展示代码 x=int(input('Enter number 1:')) y=int(input('Enter number 2:')) z=x+y print('Adding your numbers together gives:'+z) 现在,当我运行这个程序时,它一直在说“TypeError:不能隐式地将'int'对象转换为str” 我只是想让它正常运行。 有人能帮忙吗? 谢谢 您应该将最后


我对Python程序的这个问题有点困惑。这是一个非常简单的程序,但它总是出现问题。请允许我向您展示代码

x=int(input('Enter number 1:'))
y=int(input('Enter number 2:'))
z=x+y
print('Adding your numbers together gives:'+z)
现在,当我运行这个程序时,它一直在说“TypeError:不能隐式地将'int'对象转换为str”

我只是想让它正常运行。 有人能帮忙吗?

谢谢

您应该将最后一行改写为:

print('Adding your numbers together gives:%s' % z)

因为在Python中不能使用
+
符号连接
字符串
int

您的错误消息准确地告诉您发生了什么

z
是一个
int
,您试图将其与字符串连接起来。在连接它之前,必须首先将其转换为字符串。您可以使用
str()
函数执行此操作:

print('Adding your numbers together gives:' + str(z))

问题很明显,因为您无法将
str
int
连接起来。更好的方法:您可以用逗号分隔字符串和
打印
的其余参数:

>>> x, y = 51, 49
>>> z = x + y
>>> print('Adding your numbers together gives:', z)
Adding your numbers together gives: 100
>>> print('x is', x, 'and y is', y)
x is 51 and y is 49
print
功能将自动处理变量类型。以下方法也很有效:

>>> print('Adding your numbers together gives:'+str(z))
Adding your numbers together gives:100
>>> print('Adding your numbers together gives: {}'.format(z))
Adding your numbers together gives: 100
>>> print('Adding your numbers together gives: %d' % z)
Adding your numbers together gives: 100

看看你的
输入
行,找出明显的区别…@TomFenech这不是一个好的复制品。标题相似,但问题却大不相同。@JohnKugelman我接受你的观点。