Example:
>>> test4='this is hello world'
>>> test4[8:13]'hello'
>>> test4[8:13] is 'hello'
False
>>> test4[8:13] == 'hello'
True
例子中is和==都是比较的方法,但'==' 是用来比较两个对象的值是否相同( equality test),类似 'hello'.__eq__(test4[8:13])
但is比较方法是比较两个对象是不是同一个对象( identity test),相当于:
id(test4[8:13]) == id('hello')
而且这里是比较字符串,字符串有个 interned 特性(string interning is a method of storing only one copy of each distinct string value),详情见:
http://en.wikipedia.org/wiki/String_interning
所以当比较非字符串时:
>>> [1, 2] == [1,2]
True
>>> [1, 2] is [1,2]
False
参考资料:
http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce
http://blog.youkuaiyun.com/sasoritattoo/article/details/12451359
http://en.wikipedia.org/wiki/String_interning