Why is not working when comparing the replace of a string?

3

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

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

But returned False

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

Does anyone have any logical explanation for this?

    
asked by anonymous 10.10.2016 / 05:41

1 answer

2

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

In short:

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

There you compare me: ah, but 'foobar' is 'foobar' returns true .

True, but this is because Python caches small values, so this is comparison can be confusing, please 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

    
10.10.2016 / 05:43