String Caching Mechanism in Python

Similar to integer caching, Python caches commonly used strings to avoid frequent memory allocation/deallocation and fragmentation, improving performance.

Rules:

Cached strings contain only underscores, digits, and letters.

The first creation of such a string adds it to the cache; subsequent identical strings reuse the cached object.

Examples:

code.python
>>> a = 'abc'
>>> b = 'abc'
>>> a == b  # True(same value)
>>> a is b  # True(same cached object)
>>> a = 'abc 123'  # Contains space(not cached)
>>> b = 'abc 123'
>>> a is b  # False(different objects)