tan
tan

Reputation: 301

Comparing two variables in Python

I'm trying to test for equality of a and b here. I'm not sure why the output prints 'not equal' even though both a and b equates to '75', which is the same value.

a = (len(products)) #products is a dictionary, its length is 75
b = (f.read()) #f is a txt file that contains only '75'

if(str(a) == str(b)):
    print ('equal')
else:
    print ('not equal')

Upvotes: 0

Views: 12539

Answers (2)

cs95
cs95

Reputation: 403128

Add an int() around the f.read() to typecast the str to an int.

>>> b = f.read().strip() # call strip to remove unwanted whitespace chars
>>> type(b)
<type 'str'>
>>>
>>> type(int(b))
<type 'int'>
>>>
>>> b = int(b)

Now you can compare a and b with the knowledge that they'd have values of the same type.

File contents are always returned in strings/bytes, and you need to convert/typecase accordingly.

Upvotes: 3

Walkire
Walkire

Reputation: 1

The value of 'a' is 75 the integer while the value of 'b' is "75" the string. When calculated if equal the result will be false because they are not the same type. Try casting b to an integer with:

b = int(b)

Upvotes: 0

Related Questions