Python如何判定字符串是否相同?为何相等字符串内存地址有差异?
Great question—this gets to the heart of how Python handles string interning (the process of reusing string objects to save memory) and when it decides to cache strings. Let's break down your examples one by one, starting with the basics:
First, a quick recap:
- To check if two strings have the same content, you use the
==operator—this is what you should almost always rely on for equality checks. - The
id()function returns the memory address of an object. If two variables share the sameid(), they're pointing to the exact same object in memory.
Now let's unpack your code:
Example 1: Literal strings
s1 = "Hello" s2 = "Hello" print(id(s1) == id(s2)) # True
Python automatically interns string literals (fixed, hardcoded strings) at compile time. Since "Hello" is a static literal that doesn't change, Python stores it in a dedicated string pool and reuses the same object for every occurrence of the literal. That's why s1 and s2 share the same memory address.
Example 2: Compile-time constant expressions
s1 = "Hello" * 3 s2 = "Hello" * 3 print(id(s1) == id(s2)) # True
Even though this uses the * operator, Python's compiler can compute the final result ("HelloHelloHello") at compile time—it's a constant expression with no variables involved. The compiled code directly uses this precomputed string literal, which gets interned just like the literal in Example 1. Hence, s1 and s2 point to the same object.
Example 3: Runtime-generated strings
i = 3 s1 = "Hello" * i s2 = "Hello" * i print(id(s1) == id(s2)) # False
Here, i is a variable—Python can't know its value at compile time, so the string is generated on the fly at runtime. By default, Python doesn't intern dynamically generated strings like this. Even though the content is identical, each Hello" * i call creates a brand new string object in memory, which is why their id() values differ.
Bonus: Forcing interning
If you want runtime-generated strings to share the same memory address, you can use sys.intern() to explicitly add them to the string pool:
import sys i = 3 s1 = sys.intern("Hello" * i) s2 = sys.intern("Hello" * i) print(id(s1) == id(s2)) # Now True!
Key Takeaway
Never use id() to check if strings are "equal"—stick with == instead. String interning is an optimization Python uses to save memory, but it's not guaranteed for all strings. The core rule here is: compile-time constants get interned, while runtime-generated strings usually don't.
内容的提问来源于stack exchange,提问作者Mike Scotty

