Home > other >  String removal in for loop
String removal in for loop

Time:02-18

New here and new to coding really. Any help would be great. I am sorry if I do not get the proper format of the forum or community. Also, my terminology for coding discussion may be off as well.

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.

Any help is appreciated. Thank you.

CodePudding user response:

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.

CodePudding user response:

I will give you a hint and hope you can proceed further.

After replacing 'aa' with '', when you go to second iteration it starts checking from second 'b' because the value of j is 1. As you are looping over and modifying the same string, the result is not what you expect.

  • Related