Home >Backend Development >Python Tutorial >Does Python Intern Strings at Compile Time or Run Time, and How Does This Affect Comparisons?
Understanding Python String Interning
String interning is a mechanism where multiple strings with the same content share the same object in memory. Python employs string interning to optimize string handling and reduce memory usage.
Compile-Time String Interning
The first two examples demonstrate compile-time string interning. Both strings ("string" and "strin" "g") are evaluated and converted to the same immutable string object at compile time. This results in both strings being equivalent and occupying the same memory address.
Run-Time String Evaluation
However, the third example involves a run-time concatenation of strings. Unlike the compile-time concatenation, the result of this operation is not automatically interned. Hence, "s1 "g" and "string" occupy different memory addresses, resulting in the comparison "s1 "g" is "string" returning False.
Controlling String Interning
You can manually intern a string using sys.intern(). By doing so, you ensure that the string literal you pass is the same object as the existing string value if it exists.
Implementation Details
String interning behavior depends on the specific Python implementation. CPython (the most common Python implementation) interns compile-time constants but not the results of run-time expressions. This explanation applies to CPython 3.9.0 and later versions.
Note: Python 3.9 issues a warning when using "is" with string literals to compare them for equality. Instead, use "==" for this purpose.
The above is the detailed content of Does Python Intern Strings at Compile Time or Run Time, and How Does This Affect Comparisons?. For more information, please follow other related articles on the PHP Chinese website!