0

In my python code, a user enters a mathematical expression. I want to replace the variables with integer values and calculate the result. I can user regular expression in python to replace the variables with integer values but I cant calculate the sum as the replaced string I get is of type string. I can do it in tcl. It has a built in expr command where I simply pass the string and it automatically converts it to mathematical expression and calculates the result. Is there a way to do the same in python?

Thank you

user3723326
  • 115
  • 2
  • 7
  • We can't work for you, try and come back with errors and doubts. – PepperoniPizza Jun 09 '14 at 17:50
  • Could you possibly give us an expected input and expected output/method? That would at least give us something to work with. – Bob Jun 09 '14 at 17:54
  • Welcome to Stack Overflow! It's always important to tell people [what you have tried](http://whathaveyoutried.com/), including snippets of any failed attempts so that they can understand what avenues you have missed. It's important because it motivates people to answer and it's important because it makes it *easier* to give high quality, relevant answers. With the current state of the question, this hasn't been achieved. If you edit the question, it's possible that the question can be prevented from being closed and the quantity, quality and clarity of answers you get will improve as well. – Veedrac Jun 09 '14 at 18:52

1 Answers1

1

Yes there is eval. for example:

a=3
b=4
s="(a*a+b*b)**.5"
eval(s)

But be warned it maybe an security risk. You may better use SymPy http://sympy.org/en/index.html

Lee
  • 1,427
  • 9
  • 17
  • Don't use `eval()` unless you really really know what you are doing, and even then, just don't. Instead use `ast.literal_eval()` which is safe from malicious input. – Dima Tisnek Jun 09 '14 at 18:40
  • @qarma Whilst I agree `eval` is *often* a bad idea (and *definitely* is in this case), `literal_eval` won't work in this case. – Veedrac Jun 09 '14 at 18:48
  • The correct duplicate is here: http://stackoverflow.com/questions/7006626/how-to-calculate-expression-using-sympy-in-python – Lee Jun 09 '14 at 18:55
  • Sorry I did not include my code. My code looks like this: – user3723326 Jun 09 '14 at 23:12
  • list=[1.0, 3,45, 5.65] string="x**2+y**2+z**2 Now I want to replace x,y and z with the list[0], list[1] and list[2] and then calculate the result. In tcl I can do the replacement by using 'regsub' and then giving the result to 'expr' to calculate the value. Thanks Lee I can try eval – user3723326 Jun 09 '14 at 23:18