Adding character to a string

Asked

Viewed 3,392 times

1

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

i have the following variable

>>> a = "EXAMPLE"

Let’s assume I had to remove the letter "M" right string, in this case I would

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

Then knowing that the strings are immutable, if by chance I wanted to return with string "M" in the same position, so that it returns to its original format that would be EXAMPLE". Thank you.

  • 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.

1 answer

3


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)

  • understood, it worked perfectly. This Intern that you reported would be in case I manipulate data in memory. That would be it

  • 1

    No, the intern simply ensures that two equal strings (at the same time of execution) are represented by the same object. That is, if you place a string returned by intern into a data structure, and then tries to search that structure using a string also returned by intern, then he can find this data without having to compare character by character, looking only at the memory address. However, I don’t know what Python data structures take advantage of this fact, nor how it works internally.

  • All right, thanks a lot Thanks a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.