Python 中的字符串比较:is vs. == [英] String comparison in Python: is vs. ==

查看:30
本文介绍了Python 中的字符串比较:is vs. ==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到我正在编写的一个 Python 脚本表现得很奇怪,并追踪到一个无限循环,其中循环条件是 while line is not ''.在调试器中运行它,结果发现该行实际上是 ''.当我将其更改为 !='' 而不是 is not '' 时,它运行良好.

I noticed a Python script I was writing was acting squirrelly, and traced it to an infinite loop, where the loop condition was while line is not ''. Running through it in the debugger, it turned out that line was in fact ''. When I changed it to !='' rather than is not '', it worked fine.

此外,即使在比较 int 或 Boolean 值时,默认情况下也只使用=="是否更好?我一直喜欢使用is",因为我觉得它更美观,更像pythonic(这就是我落入这个陷阱的原因......),但我想知道它是否只是在你关心找到两个时保留具有相同 ID 的对象.

Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values? 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.

推荐答案

对于所有内置的 Python 对象(比如字符串、列表、字典、函数、等),如果 x 是 y,那么 x==y 也是没错.

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

并非总是如此.NaN 是一个反例.但是通常,身份(is)意味着相等(==).反之则不然:两个不同的对象可以具有相同的值.

Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.

此外,通常认为默认情况下只使用 '==' 是否更好,即使比较 int 或 Boolean 值时?

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

比较值时使用 ==,比较身份时使用 is.

You use == when comparing values and is when comparing identities.

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

When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is, but don't rely on it.

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

For boolean values, you shouldn't be doing comparisons at all. Instead of:

if x == True:
    # do something

写:

if x:
    # do something

为了与 None 进行比较,is None 优于 == None.

For comparing against None, is None is preferred over == None.

我一直喜欢使用是",因为我觉得它更美观和pythonic(这就是我陷入这个陷阱...),但我想知道它是不是打算只保留给什么时候使用你关心找到两个对象具有相同的 ID.

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.

是的,这正是它的用途.

Yes, that's exactly what it's for.

这篇关于Python 中的字符串比较:is vs. ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆