3

I run this command in python console:

why the 2 results are different?

>>>S1 = 'HelloWorld'
>>>S2 = 'HelloWorld'
>>>S1 is S2
True
>>>S1 = 'Hello World'
>>>S2 = 'Hello World'
>>>S1 is S2
False                ---------i think the result is True,why it is False
Sigma65535
  • 361
  • 4
  • 15
  • 1
    That's a common behaviour. See the following thread: [Identity testing vs Equality testing](http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce) –  Feb 21 '17 at 09:05
  • In particular, see [this answer](http://stackoverflow.com/a/1504848/5014455) from the duplicate. – juanpa.arrivillaga Feb 21 '17 at 09:20
  • While running code with **pycharm,** in both the cases it gives `true` – Chanda Korat Feb 21 '17 at 09:25

1 Answers1

0

is the result will be true only if the object is the same object.

== will be true if the values of the object are the same.

>>> S1 = 'HelloWorld'
>>> print id(S1)
4457604464
>>> S2 = 'HelloWorld'
>>> print id(S2)
4457604464
>>> S1 is S2
True

The above code means S1 and S2 are same object.And they have the same memory location.So S1 is S2.

>>> S1 = 'Hello World'
>>> S2 = 'Hello World'
>>> print id(S1)
4457604320
>>> print id(S2)
4457604272
>>> S1 is S2
False

Now,they're different object,so S1 is not S2.

McGrady
  • 10,869
  • 13
  • 47
  • 69
  • >>>S1 = 'Hello World' >>>S2 = 'Hello World' >>>S1 is S2 False ----- i think the result is True,why it is False – Sigma65535 Feb 21 '17 at 09:09
  • 1
    @Sigma65535 because `S1` and `S2` are *not the same object*. – juanpa.arrivillaga Feb 21 '17 at 09:17
  • 1
    Than earlier, when there is no space between Hello and world, why they have same id? – Chanda Korat Feb 21 '17 at 09:21
  • 1
    @ChandaKorat Read the info about string interning in Daniel Pryden's answer in the linked question. Sometimes you get interning, sometimes you don't. Interning is mainly designed for caching valid Python identifiers (eg, the names of variables and attributes), so strings that could be valid identifiers are more likely to be interned. – PM 2Ring Feb 21 '17 at 09:28
  • @PM2Ring yeah thanks...!! – Chanda Korat Feb 21 '17 at 09:30