为什么我在非常基本的Python脚本中出现此错误?错误是什么意思?
错误:
Traceback (most recent call last):
File "cab.py", line 16, in <module>
if cab in line:
TypeError: 'in <string>' requires string as left operand, not int
脚本:
import re
import sys
#loco = sys.argv[1]
cab = 6176
fileZ = open('cabs.txt')
fileZ = list(set(fileZ))
for line in fileZ:
if cab in line:
IPaddr = (line.strip().split())
print(IPaddr[4])
答案 0 :(得分:19)
您只需要将cab
设为字符串:
cab = '6176'
如错误消息所示,您无法执行<int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
因为integers和strings是两个完全不同的东西,Python不包含隐式类型转换("Explicit is better than implicit.")。
实际上,如果左操作数也是string类型的话,Python only 允许你使用in
运算符和一个类型为string的右操作数:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>