I'm new to python and am having trouble comparing two elements. One element is from an array that I created using the readlines() method on a text file, and the other is just a variable I assigned a value. I have code that looks something like
f=open('graph.txt')
graph=f.readlines()
f.close()
node=0
print graph[0][0]
print node
print graph[0][0]==node
and it prints
0
0
False
Why is the double equals giving a false, when the two items print the same value? Is it because they are different types, or something like that? Thanks!
1 Answer 1
You are comparing strings and integers. Convert one or the other:
graph[0][0] == str(node)
or
int(graph[0][0]) == node
or make node a string to begin with:
node = '0'
Note that '0' and 0 (string and integer values) print the same:
>>> print '0'
0
>>> print 0
0
Use repr() to make the difference clear:
>>> print repr('0')
'0'
>>> print repr(0)
0