Replace a substring in a string according to a list

Viewed 81

According to tutorialspoint:

The method replace() returns a copy of the string in which the occurrences of old have been replaced with new. https://www.tutorialspoint.com/python/string_replace.htm

Therefore one can use:

>>> text = 'fhihihi'
>>> text.replace('hi', 'o')
'fooo'

With this idea, given a list [1,2,3], and a string 'fhihihi' is there a method to replace a substring hi with 1, 2, and 3 in order? For example, this theoretical solution would yield:

'f123'
4 Answers

You can create a format string out of your initial string:

>>> text = 'fhihihi'
>>> replacement = [1,2,3]
>>> text.replace('hi', '{}').format(*replacement)
'f123'

Use re.sub:

import re

counter = 0

def replacer(match):
    global counter
    counter += 1
    return str(counter)

re.sub(r'hi', replacer, text)

This is going to be way faster than any alternative using str.replace

One solution with re.sub:

text = 'fhihihi'
lst = [1,2,3]

import re
print(re.sub(r'hi', lambda g, l=iter(lst): str(next(l)), text))

Prints:

f123

Other answers gave good solutions. If you want to re-invent the wheel, here is one way.

text = "fhihihi"
target = "hi"

l = len(target)
i = 0
c = 0
new_string_list = []
while i < len(text):
    if text[i:i + l] == target:
        new_string_list.append(str(c))
        i += l
        c += 1
        continue
    new_string_list.append(text[i])
    i += 1

print("".join(new_string_list))

Used a list to prevent consecutive string creation.

Related