Python 类型错误:'in <string>' 需要字符串作为左操作数,而不是 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24831961/
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
TypeError: 'in <string>' requires string as left operand, not int
提问by teamg
Why am I getting this error in the very basic Python script? What does the error mean?
为什么我会在非常基本的 Python 脚本中收到此错误?错误是什么意思?
Error:
错误:
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
Script:
脚本:
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])
采纳答案by teamg
You simply need to make cab
a string:
你只需要创建cab
一个字符串:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
正如错误消息所述,您不能执行以下操作<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
>>>
because integersand stringsare two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
因为整数和字符串是两个完全不同的东西,而且 Python 不支持隐式类型转换(“显式优于隐式。”)。
In fact, Python onlyallows you to use the in
operator with a right operand of type string if the left operand is also of type string:
实际上,如果左操作数也是字符串类型,Python只允许您将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
>>>
回答by Aman Gupta
import re
import sys
#loco = sys.argv[1]
cab = str('6176')
fileZ = open('cabs.txt')
fileZ = list(set(fileZ))
for line in fileZ:
if cab in line:
IPaddr = (line.strip().split())
print(IPaddr[4])