Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String removal in for loop

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading