【问题标题】:compare two group string,return different results [duplicate]比较两组字符串,返回不同的结果[重复]
【发布时间】:2017-02-21 09:03:14
【问题描述】:

我在 python 控制台中运行这个command

为什么两个结果不同?

>>>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

【问题讨论】:

标签: python


【解决方案1】:

is 只有当对象是同一个对象时,结果才会为真。

如果对象的值相同,== 将为真。

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

上面的代码意味着S1S2是同一个对象,并且它们有相同的内存位置。所以S1S2

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

现在,它们是不同的对象,所以 S1 不是 S2

【讨论】:

  • >>>S1 = 'Hello World' >>>S2 = 'Hello World' >>>S1 is S2 False -----我认为结果是True,为什么是False
  • @Sigma65535 因为S1S2 不是同一个对象
  • 相比之前,Hello 和 world 之间没有空格,为什么它们的 id 相同?
  • @ChandaKorat 阅读 Daniel Pryden 在链接问题中的回答中有关字符串实习的信息。有时你会实习,有时你不会。实习主要用于缓存有效的 Python 标识符(例如,变量和属性的名称),因此可能是有效标识符的字符串更有可能被实习。
  • @PM2Ring 是的,谢谢...!!
猜你喜欢
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 2019-12-21
  • 2018-09-02
  • 2016-01-10
相关资源
最近更新 更多