两个字符串变量被设置为相同的值。s1 == s2总是返回True,但s1 = s2有时返回False。
如果我打开我的Python解释器,并做同样的比较,它成功了:
>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True
为什么会这样?
两个字符串变量被设置为相同的值。s1 == s2总是返回True,但s1 = s2有时返回False。
如果我打开我的Python解释器,并做同样的比较,它成功了:
>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True
为什么会这样?
当前回答
is是身份测试,==是相等测试(请参阅Python文档)。
在大多数情况下,如果a是b,那么a == b。但也有例外,例如:
>>> nan = float('nan')
>>> nan is nan
True
>>> nan == nan
False
所以,你只能在同一性测试中使用is,而不是相等性测试。
其他回答
is关键字是测试对象身份,而==是值比较。
如果使用is,当且仅当对象是同一对象时,结果将为真。但是,当对象的值相同时,==将为真。
实际上,is操作符检查是否相同,而==操作符检查是否相等。
从语言参考:
Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)
因此,从上面的语句中,我们可以推断出字符串是不可变类型,当使用"is"检查时可能会失败,而当使用"is"检查时可能会成功。
同样适用于int和tuple,它们也是不可变类型。
如果你不确定你在做什么,使用'=='。 如果你对它有更多的了解,你可以用'is'来表示已知的对象,比如'None'。
否则,你最终会想知道为什么事情不管用,为什么会发生这种情况:
>>> a = 1
>>> b = 1
>>> b is a
True
>>> a = 6000
>>> b = 6000
>>> b is a
False
我甚至不确定在不同的Python版本/实现之间是否保证有一些东西保持不变。
基本概念,我们必须清楚,在处理这个问题时,是理解is和==之间的区别。
is将比较内存位置。如果id(a)==id(b),则a是b返回true,否则返回false。
所以,我们可以说is是用来比较内存位置的。然而,
==用于相等性测试,这意味着它只比较结果值。下面显示的代码可以作为上述理论的一个例子。
Code
对于字符串字面值(未分配给变量的字符串),内存地址将与图中所示相同。所以,id (a) (b) = = id。剩下的是不言自明的。
最后需要注意的是,你可以使用sys.intern函数来确保你得到的是同一个字符串的引用:
>>> from sys import intern
>>> a = intern('a')
>>> a2 = intern('a')
>>> a is a2
True
正如在前面的回答中指出的,您不应该使用is来确定字符串的相等性。但这可能有助于了解您是否有一些奇怪的要求使用is。
注意,intern函数曾经是Python 2的内置函数,但在Python 3中被移到了sys模块中。