比较两个相同的字符串,但在IDLE中得到不同的结果 [英] Compare two same strings but get different results in IDLE

查看:79
本文介绍了比较两个相同的字符串,但在IDLE中得到不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows 7 x64上使用带有内置IDLE的python 2.7.2,发现了一个很奇怪的东西:

I'm using python 2.7.2 with built-in IDLE on windows 7 x64, and found a very strange thing:

>>> a = "aaa"
>>> b = "aaa"
>>> print a is b
True
>>> print a == b
True
>>> print "%s , %s" % (id(a), id(b))
43872224 , 43872224
>>> 

这是正常现象,但是,如果字符串中包含空格:

This is normal, but, if the string contains a space:

>>> x = "x x"
>>> y = "x x"
>>> print x is y
False
>>> print x == y
True
>>> print "%s , %s" % (id(x), id(y))
43872008 , 43872128
>>> 

注意 x是y False !他们有不同的ID!

Notice x is y is False! And they have different ids!

我在PyCharm中尝试了这些代码,一切都返回了 True ,所以我认为这可能是IDLE的错误.

I tried these code in PyCharm, everything returns True, so I think this is may be a bug of IDLE.

不是吗?还是我想念什么?

Isn't it? Or do I miss something?

推荐答案

Python的 is 运算符实际上检查是否传递的参数是同一对象,因此在这种情况下,它们是相同的值他们不是同一个对象.

Python's is operator actually checks to see if the parameters it's passed are the same object, so in this case whilst they are the same value they're not the same object.

这实际上已经在此处进行了讨论:具有更多详细信息也值得一试.

This has actually been discussed here before: with a lot more detail as well, worth checking out.

这篇关于比较两个相同的字符串,但在IDLE中得到不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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