gpt4 book ai didi

python - “在 <字符串>”中类型错误 : How to compare input string to a list(array)

转载 作者:行者123 更新时间:2023-11-30 23:05:03 25 4
gpt4 key购买 nike

我有一个字符串值列表,并将控制台的输入与列表进行比较,然后返回值+返回它。就像错误消息建议的那样,我尝试了不同的方法,例如包括 str(var) 类型转换,但它会导致“can't allocate to function cal”。我这里的错误是什么。

In [14]: IDList = ["0002","0001"]
...:
...: def getID():
...: ID = input("Type in serial no. to use --> ")
...: for e in IDList:
...: if ID in e:
...: Analyze = e
...: break
...: else:
...: pass
...: print "Analyzing ID no.", Analyze
...: return Analyze

In [15]: getID()

Type in serial no. to use --> 0002
Traceback (most recent call last):

File "<ipython-input-15-c3fcb5192f61>", line 1, in <module>
getID()

File "<ipython-input-14-3026f1ad3d65>", line 12, in getID
if ID in e:

TypeError: 'in <string>' requires string as left operand, not int

最佳答案

input() 会将 0002 解释为 int。您应该使用 raw_input()0002 解释为字符串。

def getID():
ID = raw_input("Type in serial no. to use --> ")
for e in IDList:
if ID in e:
Analyze = e
break
else:
pass
print "Analyzing ID no.", Analyze
return Analyze

关于python - “在 <字符串>”中类型错误 : How to compare input string to a list(array),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com