3

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
  • is your list of words sorted? Commented Dec 15, 2016 at 5:36
  • Yes it is, the problem I think is it's not comparing words correctly Commented Dec 15, 2016 at 5:41
  • 3
    Try print(repr(dictionary[0])), you may have some extra characters hidden in dictionary[0]. Commented Dec 15, 2016 at 7:53
  • Maybe the str from the dicht is actually "A " (the letter A plus a space). Also print out the types of the bars to make sure they're the same. Commented Dec 15, 2016 at 7:54
  • Also, you may be comparing unicode to bytes strings Commented Dec 15, 2016 at 7:54

4 Answers 4

1

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] )
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.