Search code examples
pythonpairwisepairingbraces

Python: Get part of string between appropriate braces and symbols


For if i have the following in a text file:

{
fun cake(){
"im cute"
subfun notcake(){
"dont close the question!"
}
}
fun notcute(){
"Did you just say..."
}
}

i want to get the stuff between two braces of the fun cake(). Those particular braces, and matching pairs with opening and closing braces so that i dont get the strings of other braces.

(the focused point is highlighted in bold)


Solution

  • Here's a general purpose library function I've created for you

    def makePairs(code: str, bracket_list = ['[', '{', '(', '<']) -> dict:
        """
        Pair Maker
        =========
            Finds and creates corresponding pairs of all types of brackets given in the 'bracket_list' present in the 'code'.
    
            Parameters
            ----------
            1. Code : str - given string of code
            2. Bracket List : list - all types of brackets whose pair has to be searched and mapped
    
            Returns
            -------
            A dictionary that maps an opening bracket position to corresponding closing bracket position
    
            Example
            -------
            >>> bracePairs = makePairs(code)\n
            >>> for open, close in bracePairs.items():\n
            >>>    print(code[open : close+1])
        """
        
        naivePairs = { '{':'}', '[':']', '(':')', '<':'>' }
        pairs:dict = {}                                                         # maps '{' position to corresponding '}' position
        openBraceStack = []                                                     # will store the consecutive brace openings
        for pos, char in enumerate(code):
            if char in naivePairs.keys(): openBraceStack.append(pos)            # if char is '{', push it into the 'openBraceStack'
            elif char in naivePairs.values(): pairs[openBraceStack.pop()] = pos # if char is '}', pop the last '{' from 'openBraceStack' and store this pair into 'pairs'
        
        return pairs
    

    Usage (Have also provided in it's docstring):

    bracePairs = makePairs(code)
    for open, close in bracePairs.items():
       print(code[open : close+1], '\n\n\n')
    

    Query specific usage:

    bracePairs = makePairs(code)
    cakeOpen = code.find('{', code.find('fun cake'))            # find the first '{' after cake function
    cakeCode = code[cakeOpen + 1 : bracePairs[cakeOpen]]
    print(cakeCode)