from re import findall
from itertools import zip_longest
def change_subs(text, old_sub, new_sub, pos=[1]):
subs = findall(old_sub, text)
for i in pos: subs[i-1] = new_sub
words = zip_longest(text.split(old_sub), subs, fillvalue='')
return ''.join(''.join(elem) for elem in words)
Пример:
text = 'AAAAdfkjvsAAAA dsjfrfls d AAAAskdnfijdnAAAA kdferjnks AAAAjdfnjAAAA'
old = 'AAAA'
new = 'BB'
pos = [2,3,4]
a = change_subs(text, old, new, pos)
print(a)
In [28]:
AAAAdfkjvsBB dsjfrfls d BBskdnfijdnBB kdferjnks AAAAjdfnjAAAA