简体   繁体   中英

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM