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

OR operation not working in removing string part

I’ve been trying to parse a string and to get rid of parts of the string using the remove() function. In order to find the part which I wanted to remove I used an OR operator. However, it does not produce the outcome I expected. Can you help me?

My code looks like this:

import numpy as np

x = '-1,0;1,0;0,-1;0,+1'

x = x.split(';')

for i in x:
    if ('+' in i) or ('-' in i):
        x.remove(i)
    else:
        continue
    
x = ';'.join(x)    
print(x)

The outcome I expect is:

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

[1,0]

Instead the outcome is:

[1,0;0,+1]

>Solution :

Modifying lists that you are currently itterating over is not a good approch. Instead take a new list and append values in else.

x = '-1,0;1,0;0,-1;0,+1'

x = x.split(';')

new = []

for i in x:
    if ('+' in i) or ('-' in i):
        pass
    else:
        new.append(i)
    
x = ';'.join(new)    
print(x)

Gives #

1,0
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