Home > Mobile >  Extract arguments from string with python function
Extract arguments from string with python function

Time:09-26

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 :(

CodePudding user response:

You can parse these expressions using the built-in ast module.

import ast

def get_args(expr):
    tree = ast.parse(expr)
    args = tree.body[0].value.args
    
    return [arg.value for arg in args]

get_args('create.copy("Node_A", "Information", False)') # ['Node_A', 'Information', False]
get_args('create.new("Node_B")') # ['Node_B']
get_args('delete("Node_C")') # ['Node_C']

CodePudding user response:

See below (tested using python 3.6)

def get_args(expr):
    args = expr[expr.find('(')   1:expr.find(')')].split(',')
    return [x.replace('"', '') for x in args]


entries = ['create.copy("Node_A", "Information", False)', "create.new(\"Node_B\")"]
for entry in entries:
    print(get_args(entry))

output

   ['Node_A', ' Information', ' False']
   ['Node_B']

CodePudding user response:

Here an example without any external modules and totally compatible with python2.7.

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: for not nested functions.

  • Related