Home >Backend Development >Python Tutorial >How Does Python String Interning Work, and What Are Its Limitations?
Exploring Python String Interning
In Python, string interning is a technique used to optimize string operations by storing unique strings in a table and assigning the same address to identical strings. This concept allows for faster comparisons and string manipulation.
When comparing two string literals, Python checks if they are interned. If they are, the comparison simply checks if they point to the same address, eliminating the need for character-by-character comparison.
Understanding Interning Through Examples
The first example, "string" is "string", returns True because the strings are interned. Python recognizes that both refer to the same string value, so they share the same address.
The clever example, "strin" "g" is "string", also evaluates to True. This works because Python evaluates the concatenation at compile time and replaces "strin" "g" with "string". Thus, the comparison becomes equivalent to the first example.
Limitations of Interning
However, interning does not apply to run-time operations. The third example, s1 = "strin"; s2 = "string"; s1 "g" is s2, returns False. This is because the concatenation s1 "g" is performed at run time and the result is not interned. Python treats it as a new string object with a different address.
Implementation Details
In CPython 3.9 , interning is performed for compile-time constants but not for run-time expressions. The bytecode for the first two examples shows that the evaluated constant "string" is interned, while the third example's bytecode reveals the absence of interning for the run-time concatenation.
The above is the detailed content of How Does Python String Interning Work, and What Are Its Limitations?. For more information, please follow other related articles on the PHP Chinese website!