Confused about `is` operator with strings

前端 未结 4 705
暗喜
暗喜 2020-12-11 17:56

The is operator compares the memory addresses of two objects, and returns True if they\'re the same. Why, then, does it not work reliably with stri

4条回答
  •  甜味超标
    2020-12-11 18:30

    is is not the same as ==.

    Basically, is checks if the two objects are the same, while == compares the values of those objects (strings, like everything in python, are objects).

    So you should use is when you really know what objects you're looking at (ie. you've made the objects, or are comparing with None as the question comments point out), and you want to know if two variables are referencing the exact same object in memory.

    In your examples, however, you're looking at str objects that python is handling behind the scenes, so without diving deep into how python works, you don't really know what to expect. You would have the same problem with ints or floats. Other answers do a good job of explaining the "behind the scenes" stuff (string interning), but you mostly shouldn't have to worry about it in day-to-day programming.

提交回复
热议问题