Python string interning

前端 未结 2 1186
终归单人心
终归单人心 2020-11-22 00:32

While this question doesn\'t have any real use in practice, I am curious as to how Python does string interning. I have noticed the following.

>>> \         


        
2条回答
  •  旧时难觅i
    2020-11-22 01:20

    Case 1

    >>> x = "123"  
    >>> y = "123"  
    >>> x == y  
    True  
    >>> x is y  
    True  
    >>> id(x)  
    50986112  
    >>> id(y)  
    50986112  
    

    Case 2

    >>> x = "12"
    >>> y = "123"
    >>> x = x + "3"
    >>> x is y
    False
    >>> x == y
    True
    

    Now, your question is why the id is same in case 1 and not in case 2.
    In case 1, you have assigned a string literal "123" to x and y.

    Since string are immutable, it makes sense for the interpreter to store the string literal only once and point all the variables to the same object.
    Hence you see the id as identical.

    In case 2, you are modifying x using concatenation. Both x and y has same values, but not same identity.
    Both points to different objects in memory. Hence they have different id and is operator returned False

提交回复
热议问题