python 比较两字符串是否相同_Python如何确定两个字符串是否相同

我试图了解Python字符串何时是相同的(即共享相同的内存位置)。但是在我的测试中,当两个相等的字符串变量共享同一个内存时,似乎没有明显的解释:import sys

print(sys.version) # 3.4.3

# Example 1

s1 = "Hello"

s2 = "Hello"

print(id(s1) == id(s2)) # True

# Example 2

s1 = "Hello" * 3

s2 = "Hello" * 3

print(id(s1) == id(s2)) # True

# Example 3

i = 3

s1 = "Hello" * i

s2 = "Hello" * i

print(id(s1) == id(s2)) # False

# Example 4

s1 = "HelloHelloHelloHelloHello"

s2 = "HelloHelloHelloHelloHello"

print(id(s1) == id(s2)) # True

# Example 5

s1 = "Hello" * 5

s2 = "Hello" * 5

print(id(s1) == id(s2)) # False

字符串是不可变的,据我所知,Python试图重用现有的不可变对象

你可能感兴趣的:(python,比较两字符串是否相同)