+:'int'和'str'的不支持的操作数类型

时间:2013-12-07 11:53:12

标签: python list python-3.x int pop

我目前正在学习Python,所以我不知道发生了什么。

num1 = int(input("What is your first number? "))
num2 = int(input("What is your second number? "))
num3 = int(input("What is your third number? "))
numlist = [num1, num2, num3]
print(numlist)
print("Now I will remove the 3rd number")
print(numlist.pop(2) + " has been removed")
print("The list now looks like " + str(numlist))

当我运行程序时,输入num1,num2和num3的数字,它会返回: 回溯(最近一次调用最后一次):

TypeError: unsupported operand type(s) for +: 'int' and 'str'

2 个答案:

答案 0 :(得分:36)

您正在尝试连接字符串和整数,这是不正确的。

print(numlist.pop(2)+" has been removed")更改为以下任何一项:

明确intstr次转化:

print(str(numlist.pop(2)) + " has been removed")

使用,代替+

print(numlist.pop(2), "has been removed")

字符串格式:

print("{} has been removed".format(numlist.pop(2)))

答案 1 :(得分:1)

试,

str_list = " ".join([str(ele) for ele in numlist])

此语句将以string格式

为您提供列表中的每个元素

print("The list now looks like [{0}]".format(str_list))

print(numlist.pop(2)+" has been removed")更改为

print("{0} has been removed".format(numlist.pop(2)))