سیف خان سیف خان - 6 months ago 3
Python Question

Why does string equality not working in this Python code as expected?

Note: Before you go and downvote or close my question, or mark it a duplicate, let me assure you that I have looked a dozens and dozens of similar questions on SO and Googled but after more than an hour, I still haven't solved this problem. No other answer solved my problem.

I have this Python code:

text = ''
text += '<' + '/' + '>'

print text, '</>'
print repr(text), repr('</>')

if text is '</>':
print 'Equal'
print 'Not equal!'

I simply want to compare two strings. For some reason, I need to concatenate characters to
one by one. I expected the if-statement to evaluate to
but it doesn't. And I am at a loss why!

Here's the output:

</> </>
'</>' '</>'
Not equal!

I am new to Python, and am using Python 2.7. Can anybody help, please?


You need to use == not is. is checks for object identity not equality.


Let's say you have foo and bar such that:

>>> foo = 'green eggs and ham'
>>> bar = 'green eggs and ham'
>>> foo is bar
>>> False
>>> foo == bar
>>> True

On my machine:

>>> id(foo)
>>> 52008832 
>>> id(bar)
>>> 52010560

Now, check this out:

>>> foobar = bar
>>> foobar is bar
>>> True

More interestingly, consider two ints. This will only work for small ints.

>>> foo = 123
>>> bar = 123
>>> foo is bar
>>> True
>>> id(foo)
>>> 1993000432 # == id(bar)

Wait, what? Why does this work? It's because ints are cached.