String manipulating in python
Question: I'm trying to make a function that will take a string an remove any blocks of
text from it. For example turning "(example) somestuff" into "somestuff"
removing any blocked text from the string. This is a single function for a
large program that is meant to automatically create directories based on the
files name and move relevant files into said folder. I think I'm running into
an endless loop but lost as to what by problem is.

    
    
    startbrackets = '[', '('
    endbrackets = ']', ')'
    digits = range(0,10)
    
    def striptoname(string):
        startNum = 0
        endNum = 0
        finished = True
        indexBeginList = []
        indexEndList = [] 
    
        while (finished):
            try:
                for bracket in startbrackets:
                    indexBeginList.append(string.find(bracket, 0, len(string)))
            except:
                print "Search Start Bracket Failed"
                wait()
                exit()
    
            # Testing Code START
            finished = False
            for i in indexBeginList:
                if i != -1:
                    finished = True
                    startNum = i
                    break
            # Testing Code END
    
            try:
                for bracket in endbrackets:
                    indexEndList.append(string.find(bracket, 0, len(string)))
            except:
                print "Search End Bracket Failed"
                wait()
                exit()
    
            # Testing Code START
            for i in indexEndList:
                if i != -1:
                    endNum = i
                    break
            # Testing Code END
    
            if(finished):
                if(startNum == 0):
                    string = string[:(endNum+1)]
                else:
                    string = string[0:startNum]
        for i in digits:
            string.replace(str(i),"")
        return string
    


Answer: Here's an approach using
[`re`](https://docs.python.org/3.2/library/re.html#re.sub):

    
    
    import re
    
    def remove_unwanted(s):
        # This will look for a group of any characters inside () or [] and substitute an empty string, "", instead of that entire group.
        # The final strip is to eliminate any other empty spaces that can be leftover outside of the parenthesis.
        return re.sub("((\(|\[).*(\)|\]))", "", s).strip()
    
    print(remove_unwanted("[some text] abcdef"))
    >>> "abcdef"
    print(remove_unwanted("(example) somestuff"))
    >>> "somestuff"
    

