Adding character to string

1

Good person my doubt and the following, I have the following situation:

I have the following variable

>>> a = "EXAMPLE"

Let's suppose I had to remove the letter "M" from the string, in this case I would do

>>> a = a.replace("M", "")

Then knowing that the strings are immutable, I happen to want to return with string "M" in the same position, so that it returns to its original format that would be EXAMPLE. p>     

asked by anonymous 29.12.2015 / 04:38

1 answer

3

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)

    
29.12.2015 / 04:55