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 :(
-
All of your strings would be syntax errors. Please provide valid data and regex.MisterMiyagi– MisterMiyagi2021年09月25日 15:12:41 +00:00Commented Sep 25, 2021 at 15:12
3 Answers 3
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']
Comments
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
Comments
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']