Python – String interning


Toutes les chaines de caractères sont stockées à des adresses mémoires différentes, sauf si elles s’apparentent à une variable : minuscules, underscores et chiffres.

a = 'hello'
b = 'hello'
print(id(a))
print(id(b))
101223256
101223256

a = 'hello, world!'
b = 'hello, world!'
print(id(a))
print(id(b))
101300784
101314608

a = 'hello_world'
b = 'hello_world'
print(id(a))
print(id(b))
101300720
101300720

a = '_this_is_a_long_string_that_could_be_used_as_an_identifier'
b = '_this_is_a_long_string_that_could_be_used_as_an_identifier'
print(id(a))
print(id(b))
98854928
98854928

a = '1_hello_world'
b = '1_hello_world'
print(id(a))
print(id(b))
101300080
101300080

a = '1 hello world'
b = '1 hello world'
print(id(a))
print(id(b))
101301488
101316528

a = 'this_is_a_long_string'
b = 'this_is_a_long_string'
print('a==b:', a == b)
print('a is b:', a is b)
a==b: True
a is b: True

a = 'hello world'
b = 'hello world'
print('a==b:', a==b)
print('a is b:', a is b)
a==b: True
a is b: False

Fermer le menu