'in <string>'类型错误:如何将输入字符串与列表(数组)进行比较

时间:2015-10-27 13:55:34

标签: python string python-2.7

我有一个字符串值列表,并将控制台的输入与列表进行比较并返回值+返回它。与msg建议的错误一样,我尝试了不同的方法,例如包括str(var)类型转换,但结果为“can't assign 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

1 个答案:

答案 0 :(得分:3)

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