Search code examples
pythonstringfunctionextractpython-re

Extract arguments from string with python function


I'm looking for a way to extract arguments embedded into python function returned to me as strings.

For example:

'create.copy("Node_A", "Information", False)'
# expected return: ["Node_A", "Information", "False"]

'create.new("Node_B")'
# expected return: ["Node_B"]

'delete("Node_C")'
# expected return: ["Node_C"]

My first approach was regular expressions like this:

re.match(r"("(.+?")")

But it returns None all the time.

How can I get list of this arguments?

BTW: I'm forced to use Python 2.7 and only built-in functions :(


Solution

  • Here an example without any external modules and totally compatible with python2.7. Slice the string w.r.t. the position of the brackets, clean it from extra white-spaces and split at ,.

    f = 'create.copy("Node_A", "Information", False)'
    i_open = f.find('(')
    i_close = f.find(')')
    
    print(f[i_open+1: i_close].replace(' ', '').split(','))
    

    Output

    ['"Node_A"', '"Information"', 'False']
    

    Remark:

    • not for nested functions.

    • the closing bracket can also be found by reversing the string

      i_close = len(f) - f[::-1].find(')') - 1