Python Glossary Русский

all Python 3Strings (str)term

Strings in memory — interning, immutability

memory

Strings in Python are immutable. Interning caches short identifier-like strings. is checks object identity, == checks equality.

Syntax

s[i] = x  # TypeError  |  id(s)  |  sys.intern(s)

Immutability has a very practical consequence: upper(), replace(), strip() and slices never edit in place, they hand back a new string, and forgetting to assign that result is the classic beginner bug. Compare strings with == only — is may appear to work on literals thanks to interning, yet fails on a string built at runtime from input or concatenation; since Python 3.8 using is against a literal also emits a SyntaxWarning.

Examples

s = 'hello'
try:
    s[0] = 'H'
except TypeError as e:
    print(e)
# → 'str' object does not support item assignment
a = 'hello'
b = 'hello'
print(a == b)
# → True
print(a is b)
# → True (интернирование коротких строк)
import sys
x = sys.intern('some_long_string')
y = sys.intern('some_long_string')
print(x is y)
# → True (принудительное интернирование)
s2 = s.replace('h', 'H')
print(s, s2)
# → hello Hello (оригинал не изменился)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy