Wednesday 7 November 2018

python - Why does comparing strings using either '==' or 'is' sometimes produce a different result?



I've got a Python program where two variables are set to the value 'public'. In a conditional expression I have the comparison var1 is var2 which fails, but if I change it to var1 == var2 it returns True.



Now if I open my Python interpreter and do the same "is" comparison, it succeeds.



>>> s1 = 'public'

>>> s2 = 'public'
>>> s2 is s1
True


What am I missing here?


Answer



is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:



>>> a = 'pub'

>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False


so, no wonder they're not the same, right?



In other words: is is the id(a) == id(b)



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...