sharathchandramandadi
sharathchandramandadi

Reputation: 540

Replace multiple instances of a sub-string with items in a list

I have a string like below:

e = "how are you how do you how are they how"

My expected output is:

out = "how1 are you how2 do you how3 are they how4"

I'm trying in the following way:

def givs(y,x):
    tt = []
    va = [i+1 for i in list(range(y.count(x)))]
    for i in va:
        tt.append(x+str(i))
    return tt

ls = givs(e, 'how')

ls = ['how1', 'how2', 'how3', 'how4']

fg = []
for i in e.split(' '):
    fg.append(i)

fg = ['how', 'are', 'you', 'how', 'do', 'you', 'how', 'are', 'they', 'how']

For every instance of 'how' in 'fg' I want to replace with items in 'ls' and finally use join function to get the required output.

expected_output = ['how1', 'are', 'you', 'how2', 'do', 'you', 'how3', 'are', 
                  'they', 'how4']

so that I can join the items by:

' '.join(expected_output)

to get:

out = "how1 are you how2 do you how3 are they how4"

Upvotes: 1

Views: 43

Answers (2)

Parsa Harooni
Parsa Harooni

Reputation: 70

There is no need to make your code complex, just add a counter and add it to every "how". At the end make the new string.

e = "how are you how do you how are they how"
e_ok = ""
count = 1
for i in e.split():
    if i == "how":
        i = i+str(count)
        count += 1
    e_ok += i + " "
print(e_ok)

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61930

You could use itertools.count:

from itertools import count

counter = count(1)

e = "how are you how do you how are they how"

result = ' '.join([w if w != "how" else w + str(next(counter)) for w in e.split()])

print(result)

Output

how1 are you how2 do you how3 are they how4

Upvotes: 2

Related Questions