Python: how to replace substrings in a string given list of indices

Viewed 2181

I have a string:

"A XYZ B XYZ C"

and a list of index-tuples:

((2, 5), (8, 11))

I would like to apply a replacement of each substring defined by indices by the sum of them:

A 7 B 19 C

I can't do it using string replace as it will match both instances of XYZ. Replacing using index information will break on the second and forth iterations as indices are shifting throughout the process.

Is there a nice solution for the problem?

UPDATE. String is given for example. I don't know its contents a priori nor can I use them in the solution.

My dirty solution is:

text = "A XYZ B XYZ C"
replace_list = ((2, 5), (8, 11))

offset = 0
for rpl in replace_list:
    l = rpl[0] + offset
    r = rpl[1] + offset

    replacement = str(r + l)
    text = text[0:l] + replacement + text[r:]

    offset += len(replacement) - (r - l)

Which counts on the order of index-tuples to be ascending. Could it be done nicer?

9 Answers
Related