L
L
leham12020-05-02 16:01:15
Python
leham1, 2020-05-02 16:01:15

How to replace the desired characters in a string with others (in certain positions)?

It is necessary for me that re.sub replaces not all found values ​​in the line, but for example only replaces from the 2nd to the 4th. How to do it? If it can't be done via re.sub, then how?

For example: there is a line: 'AAAAdfkjvsAAAA dsjfrfls d AAAAskdnfijdnAAAA kdferjnks AAAAjdfnjAAAA'
It is necessary that only the second, third and fourth AAAA be replaced by BB
This should turn out: 'AAAAdfkjvsBB dsjfrfls d BBskdnfijdnBB kdferjnks AAAA'jdfnjAA

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dmshar, 2020-05-02
@dmshar

Nothing more beautiful comes to mind. Try like this:

import re
st = 'AAAAdfkjvsAAAA dsjfrfls d AAAAskdnfijdnAAAA kdferjnks AAAAjdfnjAAAA'
old='AAAA'
new='BB'
change_list=[1,2,3]
elt_list=[]
for i,a in enumerate(list(re.finditer(old, st))):
    elt_list.append([i,a.start()])
elt_list.reverse()
for elt in elt_list:
    if elt[0] in change_list:
        st=st[:elt[1]]+st[elt[1]:].replace(old, new,1)
print(st)

Result:
AAAAdfkjvsBB dsjfrfls d BBskdnfijdnBB kdferjnks AAAAjdfnjAAAA

PS The counting of deleted fragments, of course, is from scratch.

D
Drill, 2020-05-02
@Drill

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)

Example:
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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question