[D]各位哥们姐们好!小弟有一问题Python3.2.3的
a = "abc abc"
b = "abc abc"
a is b 输出false
a = "abcabc"
b = "abcabc"
a is b 输出True
这是为什么啊???
-------------------------------
Double行动:
原帖分数:40
帖子加分:40
[解决办法]
貌似跟Python对象缓存有关,没有仔细研究过
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> a = "abc abc">>> b = "abc abc">>> id(a), id(b), a is b(33019104, 33019200, False)>>> c = "abcabc">>> d = "abcabc">>> id(c), id(d), c is d(33019232, 33019232, True)>>>
[解决办法]
晕倒,果然如此.....
同问,没找到答案,源码剖析中没查到原因
[解决办法]
不清楚为啥,反正同样的字符串可以不是同一个对象,如果你非要相等,试试intern函数:
intern(string)
Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.
Changed in version 2.3: Interned strings are not immortal (like they used to be in Python 2.2 and before); you must keep a reference to the return value of intern() around to benefit from it.
[解决办法]
这个问题,要看Python在构造字符串对象的时候,如何判断两个常量字符串需要在内存中是同一个对象,貌似在含有空格的字符串,Python构造两个对象,虽然他们是一样的。例如"a b"也是一样。
[解决办法]
这个问题真是不好找资料,只能理解为语言的一种特性,或是在对象引用的一种机制,期待高手解决问题
[解决办法]
很多Python入门书籍中都有介绍,Python为了提升效率做的常量缓存造成的,只要把常量做得较个性化复制给变量再比较就能得到合理的结果了,从语言设计初衷来说a is b输出True是不正确的。测试这个特点有一个常见办法就是把字符串写得足够长,就能很好地返回False了,在这个问题上纠结没意义,知道有这个风险存在就可以了,现实中也没有人会这么干,因为字符串本身就不可变的,不会带来修改上的冲突~
[解决办法]
奇怪,我是py for s60,没有你们说的现象,都是返回1也就是Ture.