Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

Question I have this Python code:

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

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

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

I simply want to compare two strings. For some reason, I need to concatenate characters to text one by one. I expected the if-statement to evaluate to True 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?

like image 862
Saif Khan Avatar asked Dec 06 '22 18:12

Saif Khan


2 Answers

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

e.g.

Let's say you have foo and bar:

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

This is true because we've aliased the variable foobar to point to bar which is a reference. Clearly, they reference the same location under this aliasing. Hence, is returns True.

More interestingly, consider two ints. This will only work for small ints (-5, 256).

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

ints (-5, 256) are cached and so ints within this range will eval to true using is for comparing object identity.

like image 167
Pythonista Avatar answered May 03 '23 23:05

Pythonista


I have never used is in my entire history with Python (That might be because I am still having trouble wrapping my head around OOP). Just use the regular equality operator ==.

like image 32
Null Spark Avatar answered May 03 '23 23:05

Null Spark