1

I'm asking this question out of curiosity, Consider the code below:

>>> s = 'apple'
>>> a = 'apple'
>>> s is a
True 

However If I add a whitespace in the string, suddenly it seems like a new object is created for 'a' and the already created object 's' is not being used.

>>> s = 'apple '
>>> a = 'apple '
>>> s is a
False

And no matter how big the word I store in the string, it works perfectly without a whitespace

>>> s = 'htfhdtygukfufydychyggdhdhdjdjdjuntmyddm75dhxyshyjkhkhkhkhkshshsh'
>>> a = 'htfhdtygukfufydychyggdhdhdjdjdjuntmyddm75dhxyshyjkhkhkhkhkshshsh'
>>> s is a
True 

What could be the reason for this behavior?

akash
  • 587
  • 4
  • 16
Akash Goel
  • 161
  • 10
  • 2
    http://guilload.com/python-string-interning/ – Chris_Rands Jun 06 '18 at 08:56
  • 1
    don't know why this has been marked duplicate, the 3 questions above don't address the issue of whitespace causing new objects to be made. – akash Jun 06 '18 at 09:06
  • 2
    These kind of questions can be asked for every python version and every python implementation since nothing is guaranteed, there are no rules as such, you can look in the source code of your particular python implementation if you wish, but I don't feel there is any point in creating an exhaustive set of new questions about python string interning – Chris_Rands Jun 06 '18 at 09:12
  • 2
    @AkashGupta Here you go [exact duplicate](https://stackoverflow.com/questions/16756699/is-operator-behaves-differently-when-comparing-strings-with-spaces) – Nick is tired Jun 06 '18 at 09:59

0 Answers0