Under which circumstances do equal strings share the same reference?

前端 未结 3 1109
南笙
南笙 2020-12-19 03:04

I have searched the web and stack overflow questions but been unable to find an answer to this question. The observation that I\'ve made is that in Python 2.7.3, if you assi

3条回答
  •  天涯浪人
    2020-12-19 03:36

    I think it's an implementation and optimization thing. If the string are short, they can (and are often?) "shared", but you can't depend on that. Once you have longer strings, you can see that they are not the same.

    In [2]: s1 = 'abc'
    In [3]: s2 = 'abc'
    
    In [4]: s1 is s2
    Out[4]: True
    

    longer strings

    In [5]: s1 = 'abc this is much longer'
    In [6]: s2 = 'abc this is much longer'
    
    In [7]: s1 is s2
    Out[7]: False
    

    use == to compare strings (and not the is operator).

    --

    OP's observation/hypothesis (in the comments below) that this may be due to the number of tokens seems to be supported by the following:

    In [12]: s1 = 'a b c'
    In [13]: s2 = 'a b c'
    
    In [14]: s1 is s2
    Out[14]: False
    

    if compared with the initial example of abc above.

提交回复
热议问题