Is this a bug? Variables are identical references to the same string in this example (Python)

后端 未结 3 1483
说谎
说谎 2021-02-15 18:57

This is for Python 2.6.

I could not figure out why a and b are identical:

>>> a = \"some_string\"
>>> b = \"some_string\"
>>>          


        
3条回答
  •  日久生厌
    2021-02-15 19:32

    Python may or may not automatically intern strings, which determines whether future instances of the string will share a reference.

    If it decides to intern a string, then both will refer to the same string instance. If it doesn't, it'll create two separate strings that happen to have the same contents.

    In general, you don't need to worry about whether this is happening or not; you usually want to check equality, a == b, not whether they're the same object, a is b.

提交回复
热议问题