Python中的字符串比较:is vs==

2024-04-25 13:20:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我注意到我正在编写的一个Python脚本动作异常,并将其跟踪到一个无限循环,循环条件是while line is not ''。在调试器中运行它,结果发现该行实际上是''。当我把它改成!=''而不是is not ''时,它工作得很好。

另外,在默认情况下使用“==”通常被认为更好吗,即使在比较int或Boolean值时也是如此?我一直喜欢使用“I s”,因为我觉得它更美观,更像Python(这就是我掉进这个陷阱的原因……),但我想知道,如果你想找到两个具有相同id的对象,它是否只是为了保留


Tags: 对象脚本idislinenot情况原因
3条回答

我想展示一个关于is==如何涉及不可变类型的小例子。试试看:

a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True

is比较内存中的两个对象,==比较它们的值。例如,可以看到Python缓存了小整数:

c = 1
b = 1
>>> b is c
True

比较值时应使用==,比较标识时应使用is。(同样,从英语的角度来看,“equals”与“is”是不同的。)

逻辑没有缺陷。声明

if x is y then x==y is also True

不应该把读成

if x==y then x is y

假定逻辑语句的逆命题为真是读者的逻辑错误。见http://en.wikipedia.org/wiki/Converse_(logic)

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

不总是这样。南是一个反例。但是通常,恒等式(is)意味着相等(==)。反之则不然:两个不同的对象可以具有相同的值。

Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?

比较值时使用==,比较标识时使用is

在比较int(或一般不可变类型)时,您几乎总是希望使用前者。有一种优化允许将小整数与is进行比较,但不依赖它。

对于布尔值,根本不应该进行比较。而不是:

if x == True:
    # do something

写入:

if x:
    # do something

None相比,首选is None而不是== None

I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.

是的,那正是它的用途。

相关问题 更多 >