Replace text at specific position

Question:

I am trying to use the replace function to replace specific spans in a text. But it ends up replacing all same strings.

text = "I played 13 times and 134 other times"
spans = [[9,11],[26,31]]

for i in spans:
    text = text.replace(text[i[0]:i[1]], "*"*len(text[i[0]:i[1]]))

prints 'I played ** times and **4 ***** times'

replacing 13 in 134 too.

Is there another way to replace this more accurately?

Asked By: Paschalis

||

Answers:

The following does what you want. It creates a new string grabbing everything up to the beginning of the span, then adds the *** and then everything after the span. Because you are replacing text with * characters instead of deleting it, the length of the string stays the same after this operation, and we are able to continue to do this for the next span (the indices of the next span will still point to the correct characters to replace).

text = "I played 13 times and 134 other times"
spans = [[9,11],[26,31]]

for i in spans:
    text = text[:i[0]] + '*'*(i[1]-i[0]) + text[i[1]:]
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.