How does Python determine if two strings are identical

前端 未结 2 1950
春和景丽
春和景丽 2020-12-14 20:35

I\'ve tried to understand when Python strings are identical (aka sharing the same memory location). However during my tests, there seems to be no obvious explanation when tw

2条回答
  •  情话喂你
    2020-12-14 21:17

    In Example 2 :

    # Example 2
    s1 = "Hello" * 3
    s2 = "Hello" * 3
    print(id(s1) == id(s2)) # True
    

    Here the value of s1 and s2 are evaluated at compile time.so this will return true.

    In Example 3 :

    # Example 3
    i = 3
    s1 = "Hello" * i
    s2 = "Hello" * i
    print(id(s1) == id(s2)) # False
    

    Here the values of s1 and s2 are evaluated at runtime and the result is not interned automatically so this will return false.This is to avoid excess memory allocation by creating "HelloHelloHello" string at runtime itself.

    If you do intern manually it will return True

    i = 3
    s1 = "Hello" * i
    s2 = "Hello" * i
    print(id(intern(s1)) == id(intern(s2))) # True
    

提交回复
热议问题