Python:为什么运算符“is”和“==”有时可以互换为字符串?

Python: Why operator “is” and “==” are sometimes interchangeable for strings?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
String comparison in Python: is vs. ==
Python string interning
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?

我不小心用了is==来交换字符串,但我发现它们并不总是相同的。

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> Folder ="locales/"
>>> Folder2 ="locales/"
>>> Folder is Folder2
False
>>> Folder == Folder2
True
>>> File ="file"
>>> File2 ="file"
>>> File is File2
True
>>> File == File2
True
>>>

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


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

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


这个问题更清楚地说明了这一点:python中的字符串比较:is与。==

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

两个具有相同值的字符串具有相同的标识,这表明python解释器正在优化,正如Daniel Roseman确认的那样:)


==运算符调用第一个对象与第二个对象比较的内部__cmp__()方法。这适用于所有的python对象,包括字符串。is运算符比较对象标识:

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its address).

例如。:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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