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

Question:

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?

Answer:

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
True

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

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

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

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