So I am trying to compare two string variables with == and it is not working for some reason. For example this code

print(dictionary[0]) print("A") print(dictionary[0] == "A") 

prints out

A A False 

I don't understand why it returns False when they are clearly equal.

6

4 Answers

it works on me

dictionary = {0:"A"} print(dictionary[0]) print("A") print(dictionary[0] == "A") result: A A True 

possible reason is the length, maybe it contain space try to use strip() to remove the space or check the length of a string len(dictionary[0])

print(dictionary[0].strip() == "A") print len( dictionary[0] ) 

Try selecting the output with your cursor - you'll see that first line contains some whitespaces. Basically, your last line is equivalent to:

print("A " == "A") 

To get rid of those empty spaces, use str.strip method:

print(dictionary[0].strip()) print("A") print(dictionary[0] == "A") 

There are also lstrip() and rstrip() methods, removing whitespaces only on the left or right side of the string.

You might be in this situation

class Alike(object): def __eq__(self, obj): """called on ==""" return False def __repr__(self): """called on print""" return "A" a_obj = Alike() print(a_obj, a_obj == "A") 

Make sure to know exactly what is stored in your dictionary. It is not because two objects prints the same way that they are equals.

You can try to make this to know more about it:

print type(dictionary[0]), len(dictionary[0]) 

Either your list contains a string with whitespaces at the end or the item number 0 is not a string, but an object, that is printed as an "A".

class hex_number: def __init__(self,number): self.number = number def __repr__(self): return '%X' % self.number d = {0:'A ', 1:hex_number(10)} for i in range(2): print '{}: <{}>; <{}> == <{}>? => {}'.format(i,d[i],d[i],"A",d[i]=="A") 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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