0

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')
5
  • 3
    The integer 75 and the string "75" are not equal. Commented Jun 13, 2017 at 18:19
  • 1
    Possible duplicate of How to compare string and integer in python? Commented Jun 13, 2017 at 18:20
  • @TemporalWolf Hi, I've tried converting it to string as well however it's output is still 'not equal' Commented Jun 13, 2017 at 18:21
  • 3
    use str(b).strip() there maybe space or newline in b Commented Jun 13, 2017 at 18:21
  • 1
    @John you would want to convert the string to int, as the string is probably "75\n": int(b) will fix the issue. Commented Jun 13, 2017 at 18:22

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.