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.
>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.
- 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 indexk. But then your loop moves on tok+1, so you skip the element that was moved into indexk. m.remove(m[k])removes the first element equal tom[k]. If there are duplicate characters in the list, this isn’t necessarily the element at indexk.
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