0

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.

Adithya
  • 35
  • 1
  • 5

2 Answers2

0

Try this if the brackets are the first and last characters:

m=input("Enter a string:")
m=m[1:-1]
print(m)

What this is doing is taking the string and setting it to all the characters in between the first character, and the last character. This effectively removes the brackets.

If the brackets are in random places and you want to remove them all, try this:

def remove_values_from_list(the_list, val):
   return [value for value in the_list if value != val]
m=input("Enter a string:")
m=remove_values_from_list(m, "(")
m=remove_values_from_list(m, ")")
0

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

Barmar
  • 741,623
  • 53
  • 500
  • 612