Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does python choose to intern a string [duplicate]

>>> s1 = "spam"
>>> s2 = "spam"
>>> s1 is s2
True
>>> q = 'asdalksdjfla;ksdjf;laksdjfals;kdfjasl;fjasdf'
>>> r = 'asdalksdjfla;ksdjf;laksdjfals;kdfjasl;fjasdf'
>>> q is r
False

How many characters should have to s1 is s2 give False? Where is limit? i.e. I am asking how long a string has to be before python starts making separate copies of it.

like image 461
krzyhub Avatar asked May 16 '12 16:05

krzyhub


People also ask

What is string interning why it Python have it?

String Interning is a process of storing only one copy of each distinct string value in memory. This means that, when we create two strings with the same value - instead of allocating memory for both of them, only one string is actually committed to memory. The other one just points to that same memory location.

What is string intern () When and why should it be used?

String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.

What does string intern () method do?

intern() The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.

What is interning a string?

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned.


2 Answers

String interning is implementation specific and shouldn't be relied upon, use equality testing if you want to check two strings are identical.

like image 106
MattH Avatar answered Sep 23 '22 07:09

MattH


If you want, for some bizarre reason, to force the comparison to be true then use the intern function:

>>> a = intern('12345678012345678901234567890qazwsxedcrfvtgbyhnujmikolp')
>>> b = intern('12345678012345678901234567890qazwsxedcrfvtgbyhnujmikolp')
>>> a is b
True
like image 23
Spaceghost Avatar answered Sep 22 '22 07:09

Spaceghost