How python string internals work?

280 Views Asked by At

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?

0

There are 0 best solutions below