Python – Inserts multiple python substrings by index ‘at same time’

Inserts multiple python substrings by index ‘at same time’… here is a solution to the problem.

Inserts multiple python substrings by index ‘at same time’

Let’s say I have a string

a = 'The dog in the street.' (so len(a)=8).
     01234567  (just adding indices for extra illustration)

Now I want to change the string to include some arbitrary word in any place, for example, from a (arbitrary-sized) dictionary:

d = {
        'w1': {'begin':'0', 'end':'3', 'w':'BIG'}
        'w2': {'being':'4', 'end':'7', 'w':'BARKED
    }

where wx contains information about the word to be inserted, field meaning:

  • Yes: The starting index of the word we want to insert after (inclusive).

  • end: The ending index of the word we want to insert after (not included).

  • w: The word to insert

So “apply” dict d to string a, and we get:

a = 'TheBIGdogBARKEDin the street.'
     0123456789...

Note that while I’ve sorted the dictionary values here so that the words to be inserted are in left-to-right order, this is not always the case.

I initially tried to do this with something like :

for word in d:
    insertion_loc = word['end']
    a = "{}{}{}".format(a[:insertion_loc], word['w'], a[insertion_loc:]) 

But when you do, the total length of the string is changed with each iteration, so the start and end indexes no longer apply to the next word in the dictionary to be inserted into the string. The only other way that immediately comes to mind is to calculate the new insertion offset based on the previously inserted substring length, and whether the current string to be inserted is inserted before or after the previously inserted substring position (which would look a bit ugly).

Is there another way? Thank you.

Solution

You can insert from the end forward so that you don’t have to think about incrementing indexes

Related Problems and Solutions