Search code examples
pythonfor-loopsubstring

String removal in for loop


I would like to check to see if a substring pair exists and then remove the pair for multiple substrings. I have tried the following:

s = 'aabbccddee'
for j in range(0, len(s)-1): 
    y = j + 1
    if s[j].lower() + s[y].lower() in ['aa', 'bb', 'cc', 'dd']:
        z = s[j] + s[y]
        s = s.replace(z, '')
else:
    print(False)

The desired output would be s = 'ee' in this case. The best I have achieved is 'bbccddee'

The range -1 was because I was getting an out of range error. This seemed to fix it.

And the z is there because s.replace(s[j].lower() + s[y].lower(), "") did not pass.


Solution

  • If your goal is to remove some substrings from s, you can simply do this:

     targets = ['aa','bb','cc','dd']
     for t in targets:
          s = s.replace(t, '')
    

    There is no need to manually check if the substring is actually there, because replace will do that anyway.