String Identity Test

Duncan Booth duncan.booth at invalid.invalid
Tue Nov 1 15:17:23 CET 2005

Thomas Moore wrote:
> I am confused at string identity test:

> Does that mean equality and identity is the same thing for strings?
Definitely not. What is actually happening is that certain string literals 
get folded together at compile time to refer to the same string constant, 
but you should never depend on this happening.

If 'a!=b' then it will also be the case that 'a is not b', but if 'a==b' 
then there are no guarantees; any observed behaviour is simply an accident 
of the implementation and could change:

>>> a="test 1"
>>> b="test 1"
>>> a is b
>>> a="test"
>>> b="test"
>>> a is b

Testing for identity is only useful in very rare situations, most of the 
time you are better just to forget there is such a test.

More information about the Python-list mailing list