2

I have a list of strings like 'cdbbdbda', 'fgfghjkbd', 'cdbbd' etc. I have also a variable fed from another list of strings. What I need is to replace a substring in the first list's strings, say b by z, only if it is preceeded by a substring from the variable list, all the other occurrences being intouched. What I have:

a = ['cdbbdbda', 'fgfghjkbd', 'cdbbd']
c = ['d', 'f', 'l']

What I do:

for i in a:
    for j in c:
        if j+'b' in i:
            i = re.sub('b', 'z', i)

What I need:

'cdzbdzda'
'fgfghjkbd'
'cdzbd'

What I get:

'cdzzdzda'
'fgfghjkbd'
'cdzzd'

all instances of 'b' are replaced. I'm new in it, any help is very welcome. Looking for answer at Stackoverflow I have found many solutions with regex based on word boundaries or with re either with str.replace based on count, but I can't use it as the lenght of the string and number of occurrences of 'b' can vary.

3 Answers 3

1

I think if you include j in the find and replace, you'll get what you want.

>>> for i in a:
...     for j in c:
...         i = re.sub(j+'b', j+'z', i)
...     print i
... 
cdzbdzda
fgfghjkbd
cdzbd
>>> 

I added print i because your loop doesn't make in-place changes, so without that output, it's not possible to see what replacements were made.

Sign up to request clarification or add additional context in comments.

Comments

1

You should simply use regular expressions with a positive lookbehind assertion.

Like this:

import re

for i in a:
  for j in c:
    i = re.sub('(?<=' + j + ')b', 'z', i)

The base case is:

re.sub('(?<=d)b', 'z', 'cdbbdbda')

Comments

0

You can use a list comprehension:

import re
a = ['cdbbdbda', 'fgfghjkbd', 'cdbbd']
c = ['d', 'f', 'l']
new_a = [re.sub('|'.join('(?<={})b'.format(i) for i in c), 'z', b) for b in a]

Output:

['cdzbdzda', 'fgfghjkbd', 'cdzbd']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.