6

可能重复:
Python 中的字符串比较:is vs. ==
Python 字符串实习
为什么在 Python 中使用 '==' 或 'is' 比较字符串有时会产生不同的结果?

我意外地使用is==for 字符串互换,但我发现并不总是相同的。

>>> Folder = "locales/"
>>> Folder2 = "locales/"
>>> Folder is Folder2
False
>>> Folder == Folder2
True
>>> File = "file"
>>> File2 = "file"
>>> File is File2
True
>>> File == File2
True
>>> 

为什么在一种情况下运算符是可互换的,而在另一种情况下不是?

4

3 回答 3

12

短字符串是为了提高效率而被保留的,因此将引用同一个对象,因此is将是正确的。

这是 CPython 中的一个实现细节,绝对不能依赖。

于 2012-10-03T09:19:50.347 回答
4

这个问题更清楚地说明了这一点:Python中的字符串比较:is vs. ==

简短的回答是:==测试相等的值,其中is测试相等的身份(通过对象引用)。

正如 Daniel Roseman 所证实的那样,2 个具有相同值的字符串具有相同的标识这一事实表明 python 解释器正在优化:)

于 2012-10-03T09:23:19.200 回答
3

==运算符调用第一个对象的内部方法__cmp__(),将其与第二个对象进行比较。这适用于所有 Python 对象,包括字符串。运算符比较对象的is身份:

每个对象都有一个标识、一个类型和一个值。对象的身份一旦创建就永远不会改变;您可能会将其视为对象在内存中的地址。'is' 运算符比较两个对象的身份;id() 函数返回一个表示其身份的整数(当前实现为其地址)。

例如:

s1 = 'abc'
id(s1) 
>>> 140058541968080
s2 = 'abc'
id(s2)
>>> 140058541968080

# The values the same due to SPECIFIC CPython behvaiour which detects 
# that the value exists in interpreter's memory thus there is no need
# to store it twice. 

s1 is s2
>>> True

s2 = 'cde'
id(s2)
>>> 140058541968040
s1 is s2
>>> False    
于 2012-10-03T09:21:57.213 回答