Python 對短字符串、標識符形式的字符串會進行 驻留,導致 id() 相同;但動態生成或包含特殊字符的字符串可能不驻留。IDLE 與腳本運行環境優化策略不同,造成觀察差異。
# script.py
a = "hello world"
b = "hello world"
print(a is b) # True (腳本編譯期優化)
# IDLE 交互式
>>> a = "hello world"
>>> b = "hello world"
>>> a is b # False (交互式逐行編譯,不一定優化)
+、join、format、讀取輸入等運行時生成的字符串 不驻留。# 編譯期常量
a = "hello"
b = "hello"
print(id(a), id(b), a is b) # 相同 True
# 動態生成
c = "hel" + "lo"
d = "".join(["h","e","l","l","o"])
print(id(a), id(c), a is c) # 不同 False
print(id(a), id(d), a is d) # 不同 False
# 強制驻留
import sys
e = sys.intern("hello world!@#") # 手動驻留
f = sys.intern("hello world!@#")
print(e is f) # True
sys.intern)。== 比較字符串內容,is 僅用於 None、單例、哨兵對象。sys.intern() 手動驻留。理解驻留機制,避免 is 誤用導致的難以復現 Bug。