为什么使用“=="或“is"比较字符串有时会产生不同的结果? [英] Why does comparing strings using either '==' or 'is' sometimes produce a different result?

查看:24
本文介绍了为什么使用“=="或“is"比较字符串有时会产生不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 程序,其中两个变量被设置为 'public' 值.在条件表达式中,我有比较 var1 is var2 失败,但如果我将其更改为 var1 == var2 它返回 True.

现在,如果我打开 Python 解释器并进行相同的是"比较,它就会成功.

<预><代码>>>>s1 = '公共'>>>s2 = '公共'>>>s2 是 s1真的

我在这里遗漏了什么?

解决方案

is 是身份测试,== 是平等测试.您的代码中发生的事情将在解释器中被模拟如下:

<预><代码>>>>a = '酒吧'>>>b = ''.join(['p', 'u', 'b'])>>>a == b真的>>>a 是 b错误的

所以,难怪它们不一样,对吧?

换句话说:a is b 等价于 id(a) == id(b)

I've got a Python program where two variables are set to the value 'public'. In a conditional expression I have the comparison var1 is var2 which fails, but if I change it to var1 == var2 it returns True.

Now if I open my Python interpreter and do the same "is" comparison, it succeeds.

>>> s1 = 'public'
>>> s2 = 'public'
>>> s2 is s1
True

What am I missing here?

解决方案

is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:

>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False

so, no wonder they're not the same, right?

In other words: a is b is the equivalent of id(a) == id(b)

这篇关于为什么使用“=="或“is"比较字符串有时会产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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