TypeError:“in<string>”需要string作为左操作数,而不是in

2024-04-28 23:30:14 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么在最基本的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])

Tags: inimport脚本moststringif错误sys
1条回答
网友
1楼 · 发布于 2024-04-28 23:30:14

您只需将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
>>> 

因为integersstrings是两个完全不同的东西,Python不接受隐式类型转换("Explicit is better than implicit.")。

实际上,如果左操作数也是string类型,Python只允许您对string类型的右操作数使用in运算符:

>>> '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
>>>

相关问题 更多 >