You could do something like this to get an expression formatted with any arguments that match. Although it doesn't work if you have for example xs
and x
as variables since x
will replace x
in xs
since I didn't handle that in this example, so be aware of that.
def get_exp(**kwargs):
print(kwargs) # left in to show how kwargs looks
inp = input('--> ')
for k, v in kwargs.items():
inp = inp.replace(k, str(v))
return inp
# Use
>>> exp = get_exp(x = 5, y = 10)
{'x': 5, 'y': 10}
--> x ** 5 + (y - 2)
>>> exp
'5 ** 5 + (10 - 2)'
>>> exp = get_exp(x = 5, y = 10)
{'x': 5, 'y': 10}
--> z + x
>>> exp
'z + 5'
As for evaluating the expression look to here on safely evaluating input using ast
module or here for pyparsing
.
If you want to use the sympy
module then here has an example on use. However be aware the sympy
isn't considered safe.