Why does "is" not work when comparing the replace of a string?

Asked

Viewed 36 times

3

I tried to do in CLI Python 2.7.6 the following command:

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

But returned False

Despite 'foo bar'.replace(" ", "") return 'foobar'

Does anyone have any logical explanation for this?

1 answer

2

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

In short:

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

Then you tell me: ah, but 'foobar' is 'foobar' returns true.

True, but that’s because Python caches small values, which is why this comparison is can generate confusion, 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 large value? A small value?

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

  • 2

    It’s a detail, but it’s not Python that caches the small values, but Cpython-the most used and official Python implementation. Other implementations may do different.

  • Opa, Pablo Almeida, I agree with what you said. These commands were made on my machine running Cpython. Thanks for the compliment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.