python – Why doesn't "is" work when comparing replace from a string?


Tried to do in CLI Python 2.7.6 the following command:

'foo bar'.replace(" ", "") is 'foobar'

But it returned False

Although 'foo bar'.replace(" ", "") returns 'foobar'

Does anyone have any logical explanation for this?


The is command compares object instance references. If the two comparison terms are references to the same object instance then is returns true. Your comparison will return true if you use the == command, it compares the values.

Summing up:

  • == is used to compare values.
  • is is for comparing references.

Then you counter me: oh, but 'foobar' is 'foobar' returns true .

True, but that's because Python caches small values, which is why this comparison can be confusing, follow:

>>> s1 = 'foo'
>>> s2 = 'foo'
>>> s1 is s2

>>> s1 = 'foo!'
>>> s2 = 'foo!'
>>> s1 is s2

>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'

>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'

How far does Python cache a value? What is a great value? A small amount?

To get deeper into the subject I recommend reading this article: Internals in Python

Scroll to Top