String Identity Test

Fredrik Lundh fredrik at pythonware.com
Tue Nov 1 09:13:51 EST 2005


Thomas Moore wrote:

> I am confused at string identity test:
>
> Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> a="test"
>>>> b="test"
>>>> a is b
> True
>>>>
>
> About identity, I think a is not b, but "a is b" returns True.

for the string literals you used, a is b:

>>> a = "test"
>>> b = "test"
>>> id(a)
10634848
>>> id(b)
10634848
>>> a is b
True
>>> a == b
True

> Does that mean equality and identity is the same thing for strings?

nope.

>>> a = "test!"
>>> b = "test!"
>>> id(a)
10635264
>>> id(b)
10636256
>>> a is b
False
>>> a == b
True

the current CPython implementation automatically interns string literals that
happens to look like identifiers.  this is an implementation detail, and nothing
you can rely on.

the current CPython implementation also "interns" single-character strings,
so most instances of, say, the string "A" will point to the same object.  this
is also an implementation detail, and nothing you can rely on.

</F> 






More information about the Python-list mailing list