About the changing id of an immutable string

后端 未结 5 1831
暗喜
暗喜 2020-11-22 03:33

Something about the id of objects of type str (in python 2.7) puzzles me. The str type is immutable, so I would expect that once it is

5条回答
  •  借酒劲吻你
    2020-11-22 04:21

    So while Python is not guaranteed to intern strings, it will frequently reuse the same string, and is may mislead. It's important to know that you shouldn't check id or is for equality of strings.

    To demonstrate this, one way I've discovered to force a new string in Python 2.6 at least:

    >>> so = 'so'
    >>> new_so = '{0}'.format(so)
    >>> so is new_so 
    False
    

    and here's a bit more Python exploration:

    >>> id(so)
    102596064
    >>> id(new_so)
    259679968
    >>> so == new_so
    True
    

提交回复
热议问题