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?
号
我不小心用了
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 >>> |
为什么在一种情况下,运算符是可互换的,而在另一种情况下则不可互换?
为了提高效率,将使用短字符串,因此将引用同一对象,因此
这是cpython中的一个实现细节,绝对不能依赖。
这个问题更清楚地说明了这一点:python中的字符串比较:is与。==
简短的回答是:
两个具有相同值的字符串具有相同的标识,这表明python解释器正在优化,正如Daniel Roseman确认的那样:)
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 |