Even if you reinsert the removed letter, you would still be creating a new string, because as you pointed out they are immutable, then both pick up and put create new objects. This can be easily checked by looking at 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 the strings are immutable, Python does not "cache" them by default. If you want a unique string - which can be compared only by the memory address (for efficiency) - you must explicitly tell Python to put it in the cache, 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 references exist for the cached string, it can be picked up by the garbage collector and a new one created in the future)