2

I need some help in removing two sets of curly brackets with string.Right now it's only removing one set. I tired to use find and rfind to find the first and last occurence of the string index and using slice method to cut out the curly brackets but it can only remove one set of it.

It should work something like that

Input: {fefeef}this{feofeow}.4849

Output this.4849

Here is my code

 def help_mmtf():
    
       while True:
    
           user_input = input("Filename?")
           text_input = str(user_input)
    
           if (text_input !=""):
               
    
                word = text_input
                
                index1 = word.find("{")
                index2 = word.find("}")
                print(index1) 
                print(index2)
    
            
                index3 = word.rfind("{")
                index4 = word.rfind("}")
    
                print(index3)
                print(index4)
               
    
                splice_input = text_input[:index1] + text_input[index4+1:]
                print(f'"{splice_input}"')
    
      else:
               
                
               break
            
aczc
  • 23
  • 2
  • 1
    Does this answer your question? [Remove text between () and \[\]](https://stackoverflow.com/questions/14596884/remove-text-between-and) – Ahmed Elashry Feb 06 '22 at 15:52

2 Answers2

4

Use sub function from re module:

import re

s = "{fefeef}this{feofeow}.4849"
out = re.sub(r'{[^}]*}', '', s)

Output:

>>> out
'this.4849'

For more explanation: Regex101

Corralien
  • 109,409
  • 8
  • 28
  • 52
0

You can use sub

import re


def help_mmtf():
    while True:

        user_input = input("Filename?")
        text_input = str(user_input)

        if (text_input != ""):
            word = text_input



            splice_input = re.sub("\{.*?\}", "", word)
            print(f'"{splice_input}"')

        else:


         break

Time complexity: O(2^m + n).

or you can use the for loop

def help_mmtf():
    while True:

        user_input = input("Filename?")
        text_input = str(user_input)

        if (text_input != ""):
            splice_input = ''

            paren = 0
            for ch in text_input:


                if ch == '{':
                    paren = paren + 1
                    splice_input = splice_input

              
        
                elif (ch == '}') and paren:
                    splice_input = splice_input
                    paren = paren - 1

                elif not paren:
                    splice_input += ch

            print(splice_input)

        else:


         break

Time complexity: O(n).

I_Al-thamary
  • 3,385
  • 2
  • 24
  • 37