Detailed Explanation of Knowledge Points of Application Scope of python String Residence Mechanism

  • 2021-12-04 10:20:40
  • OfStack

1, when the length of the string is 0 and 1.

2. A string that matches the identifier.

3. Strings only reside at compile time, not runtime.

4, integer numbers between [-5,256].

Instances


>>> str1='jiumo'
>>> str2='jiumo'
>>> str1 is str2
True
>>> id(str1)
1979078421896
>>> id(str2)
1979078421896

Expansion of knowledge points:

Time of residence

All strings of length 0 and length 1 are resident

Strings only reside at compile time, not run time


a = 'hi' # a Variable is resident 
b = ''.join(['h', 'i']) #  Variables do not reside 
print(a is b) # False

Principle

The system maintains an interned dictionary, which records the string objects that have been resident

When the string object a needs to reside, the existence of the string object is detected at interned. If the string object exists, it points to the existing string object. The reference count of a is minus 1
If not, a is recorded into interned


Related articles: