Even if you reinsert the withdrawn letter, you would still be creating a new string, because as you pointed out they are immutable, so both removing and placing create new objects. This can be easily checked by observing the id
of the object:
>>> a = "EXAMPLE"
>>> id(a)
32844376L
>>> b = a.replace("M", "")
>>> id(b)
32845176L
>>> c = b[:3] + "M" + b[3:]
>>> id(c)
32843016L
>>> c
'EXAMPLE'
Although strings are immutable, Python does not "cache" the same by default. If you want a single string - which can be compared only by the memory address (for efficiency) - you need to explicitly tell Python to cache it, using intern
:
>>> a = intern("EXAMPLE")
>>> id(a)
32843976L
>>> b = intern(a.replace("M", ""))
>>> id(b)
32844256L
>>> c = intern(b[:3] + "M" + b[3:])
>>> id(c)
32843976L
(however, if no additional reference exists for the cached string, it can be collected by the garbage collector and a new one created in the future)
Rereading your question, I’m not sure I understand the doubt. Are you wondering if "goes back" to the same object after the reinsertion of the letter "M" because it is immutable? If so, see my answer below. If it was something else you wanted to ask, please [Dit] the question clarifying it. P.S. If the doubt is not specific to Python 2.7, I suggest retaking it with just
python
.– mgibsonbr