Home > Software engineering >  replacing words after numbers in a list of strings
replacing words after numbers in a list of strings

Time:11-17

I am new to Python. I know how to replace but this is exactly what I want to do and I can't write a function for it:

Input:

list_a=['ball', 'red', '2', 'fly', 'bee' , '3' , 'bag']
list_b=['2' , '3']
x= 'Blue'

#I extracted the numbers from list_a in form of list_b=['2' , '3']. #Now I want to replace every word in list_a which is located after a number(list_b) with the string x which is 'Blue'.

so the desired output:

list_c=['ball' , 'red' , '2' , 'Blue' , 'bee' , '3' , 'Blue']

Many thanks in advance

so the desired output:

list_c=['ball' , 'red' , '2' , 'Blue' , 'bee' , '3' , 'Blue']

CodePudding user response:

below is the solution

list_a=['ball', 'red', '2', 'fly', 'bee' , '3' , 'bag']
list_b=['2' , '3']
x= 'Blue'
lst=[]
for i in list_b:
    lst.append(list_a.index(i))

print(lst)

for j in lst:
    list_a[j 1] = x
print(list_a)
  • Related