Why does the “is” keyword have a different behavior when there is a dot in the string?

后端 未结 2 548
花落未央
花落未央 2020-12-02 14:34

Consider this code:

>>> x = \"google\"
>>> x is \"google\"
True
>>> x = \"google.com\"
>>> x is \"google.com\"
False
>         


        
2条回答
  •  囚心锁ツ
    2020-12-02 14:39

    "is" is an identity test. Python has some caching behavior for small integers and (apparently) strings. "is" is best used for singleton testing (ex. None).

    >>> x = "google"
    >>> x is "google"
    True
    >>> id(x)
    32553984L
    >>> id("google")
    32553984L
    >>> x = "google.com"
    >>> x is "google.com"
    False
    >>> id(x)
    32649320L
    >>> id("google.com")
    37787888L
    

提交回复
热议问题