最佳答案
While this question doesn't have any real use in practice, I am curious as to how Python does string interning. I have noticed the following.
>>> "string" is "string"
True
This is as I expected.
You can also do this.
>>> "strin"+"g" is "string"
True
And that's pretty clever!
But you can't do this.
>>> s1 = "strin"
>>> s2 = "string"
>>> s1+"g" is s2
False
Why wouldn't Python evaluate s1+"g"
, and realize it is the same as s2
and point it to the same address? What is actually going on in that last block to have it return False
?