0
>>> a = "asd" 
>>> b = "asd"
>>> id(a), id(b) 
(54742848, 54742848) 

>>> a = "asd!" 
>>> b = "asd!" 
>>> id(a), id(b)
(52458624, 54742016)
>>> 

Why did python creat different objects in case of "asd!" while keeping the reference same for "asd"? In general, addition of a special character to the string changes the interning behavior. Is that a rule by itself?

neotricks
  • 49
  • 8
  • Also see [here](http://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs) and [here](http://stackoverflow.com/questions/1392433/python-why-is-hello-is-hello). – TigerhawkT3 Jan 09 '16 at 07:01
  • @TigerhawkT3: Well, I disagree. OP's asking for *why `a is b` is `True`* when `a` and b both is `"asd"`, but when they're `"asd!"` the output become `False`. And I can reproduce BTW. – Remi Guan Jan 09 '16 at 07:18
  • To be specific, I know that python does create different address at times without interning strings. which creates the difference between "is" and "==". Question is what rule governs this behavior? If we are looking at optimization then it should always assign the same address. On what circumstances it decides to change it? Also, I have the answer for number assignments as some range of numbers are precreated for performance reasons. What is the case for strings? – neotricks Jan 09 '16 at 07:31
  • As the main link says, "this doesn't always happen, and the rules for when this happens are quite convoluted." You can also read about it [here](http://stackoverflow.com/questions/15541404/python-string-interning) and [here](http://stackoverflow.com/questions/2123925/when-does-python-allocate-new-memory-for-identical-strings). It is an implementation detail not guaranteed by the language. – TigerhawkT3 Jan 09 '16 at 07:32
  • @TigerhawkT3 - I also observed that whenever a special character is added to the string the behavior changes immediately. >>> a = "Hello" >>> b = "Hello" >>> a is b True >>> a = "Hello-" >>> b = "Hello-" >>> a is b False >>> a = "Hello*" >>> b = "Hello*" >>> a is b False Why does a special character immediately change the interning behavior? If i can get the answer to this "one convoluted" behavior that would be fine. I am not looking for the complete string creation rules in python. – neotricks Jan 09 '16 at 07:48

0 Answers0