文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Python string compar

2023-01-31 07:13

关注
up vote484down votefavorite
150

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?

shareimprove this question
 
87  
I don't know anything about Python, but is it possible that one is comparing values while the other is comparing objects? – Cᴏʀʏ Oct 1 '09 at 15:45
6  
see: stackoverflow.com/questions/1392433/… – Nick Dandoulakis Oct 1 '09 at 15:50
 
possible duplicate of Is there a difference between `==` and `is` in Python? – AlexKM Dec 1 '14 at 13:29

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: is is the id(a) == id(b)

shareimprove this answer
 
10  
ahh same as eq? vs equal? in scheme, got it. – jottos Oct 1 '09 at 17:00
4  
There's a lot of equality predicates in Common Lisp, besides the basic hierarchy of eq, eql, equal, and equalp (the longer the name there, the more things will be found equal). – David Thornley Oct 1 '09 at 19:43
12  
Or == vs .equals() in Java. The best part is that the Python == is not analogous to the Java ==. – MatrixFrog Feb 4 '12 at 2:48
42  
+1 for including a way to create a string with the same value but as a different object. I couldn't figure one out. – Tom Dignan Jul 3 '12 at 23:57
7  
@Крайст: there is only a single None value. So it always has the same id. – SilentGhost Oct 29 '12 at 9:57

SilentGhost and others are correct here.  is is used for identity comparison, while == is used for equality comparison.

The reason this works interactively is that (most) string literals are interned by default. From Wikipedia:

Interned strings speed up string comparisons, which are sometimes a performance bottleneck in applications (such as compilers and dynamic programming language runtimes) that rely heavily on hash tables with string keys. Without interning, checking that two different strings are equal involves examining every character of both strings. This is slow for several reasons: it is inherently O(n) in the length of the strings; it typically requires reads from several regions of memory, which take time; and the reads fills up the processor cache, meaning there is less cache available for other needs. With interned strings, a simple object identity test suffices after the original intern operation; this is typically implemented as a pointer equality test, normally just a single machine instruction with no memory reference at all.

So, when you have two string literals (words that are literally typed into your program source code, surrounded by quotation marks) in your program that have the same value, the Python compiler will automatically intern the strings, making them both stored at the same memory location. (Note that this doesn't always happen, and the rules for when this happens are quite convoluted, so please don't rely on this behavior in production code!)

Since in your interactive session both strings are actually stored in the same memory location, they have the same identity, so the is operator works as expected. But if you construct a string by some other method (even if that string contains exactly the same characters), then the string may be equal, but it is not the same string -- that is, it has a different identity, because it is stored in a different place in memory.

shareimprove this answer
 
3  
Where can someone read more on the convoluted rules for when strings are interned? – Noctis SkytowerApr 11 '13 at 14:14
20  
+1 for a thorough explanation. Not sure how the other answer received so many upvotes without explaining what ACTUALLY happened. – That1Guy Apr 29 '13 at 2:07
1  
this is exactly what I thought of when I read the question. The accepted answer is short yet contains the fact, but this answer explains things far better. Nice! – Sнаđошƒаӽ Jul 19 '15 at 5:46
1  
@NoctisSkytower Googled the same and found this guilload.com/python-string-interning – Wordzilla Mar 10 at 14:41

The is keyword is a test for object identity while == is a value comparison.

If you use is, the result will be true if and only if the object is the same object. However, == will be true any time the values of the object are the same.

shareimprove this answer
 

One last thing to note, you may use the intern function to ensure that you're getting a reference to the same string:

>>> a = intern('a')
>>> a2 = intern('a')
>>> a is a2
True

As pointed out above, you should probably not be doing is to determine equality on strings. But this may be helpful to know if you have some kind of weird requirement to use is.

Note that the intern function got moved from being a built in function to being in the module sysfor Python 3.

shareimprove this answer
 

This is a side note, but in idiomatic python, you will often see things like:

if x is None: 
    # some clauses

This is safe, because there is guaranteed to be one instance of the Null Object (i.e., None).

shareimprove this answer
 

If you're not sure what you're doing, use the '=='. If you have a little more knowledge about it you can use 'is' for known objects like 'None'.

Otherwise you'll end up wondering why things doesn't work and why this happens:

>>> a = 1
>>> b = 1
>>> b is a
True
>>> a = 6000
>>> b = 6000
>>> b is a
False

I'm not even sure if some things are guaranteed to stay the same between different python versions/implementations.

shareimprove this answer
 
1  
Interesting example showing how reassigning ints makes triggers this condition. Why did this fail? Is it due to intern-ing or something else? – Paul Dec 22 '14 at 16:49
 
It looks like the reason the is returns false may due to the interpreter implementation: stackoverflow.com/questions/132988/… – Paul Dec 22 '14 at 16:55
 
Read : stackoverflow.com/questions/306313/… and  stackoverflow.com/questions/11476190/why-0-6-is-6-false – Archit Jain Dec 26 '15 at 13:04 
 
@ArchitJain Yes, those links explain it pretty well. When you read them, you'll know what numbers you can use 'is' on. I just wish they would explain why it is still not a good idea to do that :) You knowing this does not make it a good idea to assume everyone else does as well (or that the internalized number range will never change) – Mattias Nilsson Dec 29 '15 at 13:32 

is is identity testing, == is equality testing. What this means is that is is a way to check whether two things are the same things, or just equivalent. 

Say you've got a simple person object. If it is named 'Jack' and is '23' years old, it's equivalent to another 23yr old Jack, but its not the same person.

class Person(object):
   def __init__(self, name, age):
       self.name = name
       self.age = age

   def __eq__(self, other):
       return self.name == other.name and self.age == other.age

jack1 = Person('Jack', 23)
jack2 = Person('Jack', 23)

jack1 == jack2 #True
jack1 is jack2 #False

They're the same age, but they're not the same instance of person. A string might be equivalent to another, but it's not the same object.

shareimprove this answer
 
1  
@Veky I just fixed that in my edit. – Morgan 'Venti' Thrappuccino Mar 4 at 21:04

From my limited experience with python, is is used to compare two objects to see if they are the same object as opposed to two different objects with the same value.  == is used to determine if the values are identical. 

Here is a good example:

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

s1 is a unicode string, and s2 is a normal string. They are not the same type, but are the same value.

shareimprove this answer
 
 
Your example still follows the older text.... – jprete Oct 2 '09 at 16:16

I think it has to do with the fact that, when the 'is' comparison evaluates to false, two distinct objects are used. If it evaluates to true, that means internally it's using the same exact object and not creating a new one, possibly because you created them within a fraction of 2 or so seconds and because there isn't a large time gap in between it's optimized and uses the same object.

This is why you should be using the equality operator ==, not is, to compare the value of a string object.

>>> s = 'one'
>>> s2 = 'two'
>>> s is s2
False
>>> s2 = s2.replace('two', 'one')
>>> s2
'one'
>>> s2 is s
False
>>>

In this example, I made s2, which was a different string object previously equal to 'one' but it is not the same object as s, because the interpreter did not use the same object as I did not initially assign it to 'one', if I had it would have made them the same object.

shareimprove this answer
 
1  
Using .replace() as an example in this context is probably not the best, though, because its semantics can be confusing.  s2 = s2.replace() will always create a new string object, assign the new string object to s2, and then dispose of the string object that s2 used to point to. So even if you did s = s.replace('one', 'one') you would still get a new string object. – Daniel Pryden Oct 1 '09 at 16:20
 
Ah, good point and that is true. – meder omuraliev Oct 1 '09 at 16:46

I believe that this is known as "interned" strings. Python does this, so does Java, and so do C and C++ when compiling in optimized modes.

If you use two identical strings, instead of wasting memory by creating two string objects, all interned strings with the same contents point to the same memory.

This results in the Python "is" operator returning True because two strings with the same contents are pointing at the same string object. This will also happen in Java and in C.

This is only useful for memory savings though. You cannot rely on it to test for string equality, because the various interpreters and compilers and JIT engines cannot always do it.

shareimprove this answer
 

I am answering the question even though the question is to old because no answers above quotes the language reference

Actually the is operator checks for identity and == operator checks for equality,

From Language Reference:

Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)

so from above statement we can infer that the strings which is an immutable type may fail when checked with "is" and may checked succeed when checked with "is"

The same applies for int,tuple which are also immutable types

shareimprove this answer
 

Your Answer

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯