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

Unable to remove strings containing parentheses

I am trying to iterate through a list of strings and remove any which contain an open parentheses.

”’

counter = 0
for i in self.command_list:
            if i.find("(") != -1:
                self.command_list.pop(counter)
            counter = counter + 1

”’

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 if statement properly identifies if a string contains an open parentheses so why isn’t pop working?

>Solution :

command_list = ["first",
                "fir(st",
                "second",
                "(second)"]

command_list = [i for i in command_list if "(" not in i]
print(command_list)

The problem might be that you are looping through the command_list and when you pop, indexing changes on-the-fly, so you miss adjacent items.

If you don’t need to store popped items you can re-write the list as above.

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