无法将整数转换为字符串

时间:2014-03-13 17:57:38

标签: 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含义"。

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

3 个答案:

答案 0 :(得分:3)

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

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

因为您无法使用+符号在Python中连接stringint

答案 1 :(得分:3)

您的错误消息告诉您具体发生了什么。

zint,您尝试将其与字符串连接起来。在连接之前,必须先将其转换为字符串。您可以使用str()功能执行此操作:

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

答案 2 :(得分:2)

问题很明显,因为您无法连接strint。更好的方法:你可以用逗号分隔字符串和print个参数的其余部分:

>>> 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
相关问题