How can we change the id of an immutable string in Python?

PythonServer Side ProgrammingProgramming

Strings in Python are immutable, that means that once a string is created, it can't be changed. When you create a string, and if you create same string and assign it to another variable they'll both be pointing to the same string/memory. For example,

>>> a = 'hi'
>>> b = 'hi'
>>> id(a)
43706848L
>>> id(b)
43706848L

This reuse of string objects is called interning in Python. The same strings have the same ids. But Python is not guaranteed to intern strings. If you create strings that are either not code object constants or contain characters outside of the letters + numbers + underscore range, you'll see the id() value not being reused.

We change the id of the given string as follows. We assign it to two different identifiers. The ids of these variables when found are different. This is because the given string contains characters other than alphabets, digits, and underscore.

>>> a = 'weworks_45#@$'
>>> b = 'weworks_45#@$'
>>> id(a)
96226208L
>>> id(b)
91720800L
raja
Published on 13-Dec-2017 11:00:22
Advertisements