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

标签 python string comparison equality

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

此外,即使在比较 int 或 Boolean 值时,通常认为默认使用 '==' 是否更好?我一直喜欢使用'is',因为我发现它更美观和pythonic(这就是我陷入这个陷阱的原因......),但我想知道它是否只是为了当你关心找到两个时保留具有相同 id 的对象。

最佳答案

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

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

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

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

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

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

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.

是的,这正是它的用途。

关于python - Python 中的字符串比较 : is vs. ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2988017/

相关文章:

用于 Clojure 的 Python StringIO

python - 按下按钮后 Tkinter.Label 不显示

python - Pandas DataFrame 与对象的意思

python - 在包含数字和字符串的列表上使用 max()

c# - 比较不同对象但具有相同字段的 2 个列表

检查 double 是否等于 -0.00

python - 为每个文件分别创建一个新的 txt 文件,其中包含输出和输入文件的大小信息

javascript - 如何字符串替换和字符串重新排列

java正则表达式选择直到字符串而不是子字符串

php - php中是否可以进行python丰富的比较?