本文转载刘荣星的博客,原文链接:
https://www.liurongxing.com/python-is-cmp-compare-operator.html
在 Python 中比较字符串最好是使用简单逻辑操作符。
例如,确定一个字符串是否和另外一个字符串匹配。可以使用 is equal 或 == 操作符,也可以使用 >= 或 < 来确定几个字符串的排列顺序。
从官方文档看:
The operators ``is`` and ``is not`` test for object identity:
``x is y`` is true if and only if *x* and *y* are the same object.
``x is not y`` yields the inverse truth value.
cmp(...)
cmp(x, y) -> integer
Return negative if x<y, zero if x==y, positive if x>y.
也就是说:
is 用来判断是否是同一个对象。
python is 主要是判断 2 个变量是否引用的是同一个对象,如果是的话,则返回 true,否则返回 false。
判断数字相等不要用 is 操作符。
>>> a = 256
>>> b = 256
>>> id(a)
9987148
>>> id(b)
>9987148
>>> a = 257
>>> b = 257
>>> id(a)
11662816
>>> id(b)
11662828
为什么两次 is 返回的是不同结果?不是应该都是 true 吗?
因为 string pooling (或叫intern)。 is 相等代表两个对象的 id 相同(从底层来看的话,可以看作引用同一块内存区域)。 至于为什么 “ABC” 被 intern 了而 “a bc” 没有,这是 Python 解析器实现决定的,可能会变。
== 用来判断两个对象的值是否相等(跟 Java 不同,Java 中 == 用来判断是否是同一个对象)。
例如:
#-*-conding:utf-8-*-
i='xinwen';
m=input();
if i==m:
print('yes');
else:
print('no');
input();
cmp() 函数则是相当于 <,==,> 但是在 Python3 中,cmp() 函数被移除了,所以以后还是避免少用这个函数
>>> x='a'
>>> x+'b' is 'ab'
False
>>> x+'b' == 'ab'
True
>>> cmp(x+'b','ab')
0
>>> id(x+'b')
32468384L
>>> id('ab')
46933696L