TypeError: 'in <string>' requires a string as a left operand, not an int
Why am I getting this error in the most basic Python script? What does the error mean?
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])
+4
1 answer
You just need to make a cabline:
cab = '6176'
As indicated in the error message, you cannot do <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 integers and strings are two completely different things and Python doesn't use an implicit type conversion ( Explicit is better than implicit. ).
In fact, Python allows you to use an operator inwith the correct operand of a type string if the left operand also has a type 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
>>>
+16