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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20441035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:26:34  来源:igfitidea点击:

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

pythonpython-3.xlistint

提问by

I am currently learning Python so I have no idea what is going on.

我目前正在学习 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))

When I run the program, entering in numbers for num1, num2 and num3, it returns this: Traceback (most recent call last):

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

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

采纳答案by Ashwini Chaudhary

You're trying to concatenate a string and an integer, which is incorrect.

您试图连接一个字符串和一个整数,这是不正确的。

Change print(numlist.pop(2)+" has been removed")to any of these:

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

Explicit intto strconversion:

明确intstr转换:

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

Use ,instead of +:

使用,代替+

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

String formatting:

字符串格式:

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

回答by Siva Cn

try,

尝试,

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

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

this statement will give you each element of your list in stringformat

此语句将以string格式为您提供列表中的每个元素

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

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

and,

和,

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

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

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

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

as well.

以及。