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

Removing a range of elements from a string in python

I wanted to remove elements within brackets, taking a string as input.
I initially tried using the following code.

m=input("Enter a string:")
m=list(m)
print(m)
for i in m:
  k=m.index(i)
  if i=='(':
    x=m.index('(')
    y=m.index(')')
    for k in range(x,y+1,1)
    m.remove(m[k])
 m="".join(m)
 print(m)

But this code didn’t remove the elements within brackets. Instead, it removed the brackets and some elements in the first word.
I found the following code to be working.

m=input("Enter a string:")
m=list(m)
for i in m:
  k=m.index(i)
  if i=='(':
    x=m.index('(')
    y=m.index(')')
    del m[x:y+1]
m="".join(m)
print(m)

I am new to python. Though I tried several times, I couldn’t find the mistake in the first code and couldn’t see why it removed only the brackets though I specified the range correctly. It would be helpful if someone could help me with the same.

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

>Solution :

You can solve it more easily using a regular expression.

import re

m = re.sub(r'\(.*?\)', '')

Your first code didn’t work for multiple reasons.

  1. After you remove a list element, the indexes of all the following elements are reduced. So after you remove the element at index k, the next element is now at index k. But then your loop moves on to k+1, so you skip the element that was moved into index k.
  2. m.remove(m[k]) removes the first element equal to m[k]. If there are duplicate characters in the list, this isn’t necessarily the element at index k.

In general you have to be careful when modifying a list that you’re iterating over. See Strange result when removing item from a list while iterating over it

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