Peharps I have a str in Python like "8+3" or even more difficult like "sin(30)" or others. How to convert then from type of str to calculate. For eхample if i have str like "8+3" it must calculate like int numbers 8+3 = 11, or if i have str like "sin(30)" it must calculate math.sin(30).
Asked
Active
Viewed 96 times
2 Answers
0
my_string = "8+3"
my_result = eval(my_string)

Ludovic Viaud
- 202
- 1
- 5
-
Note that for the `sin(30)` example, for this solution to work you must do `from math import *` – Cory Kramer Nov 17 '14 at 18:17
-
1
-
Well yes, but you would have to anticipate every single function that could be in the string that you are `eval`ing. `from math import sin`, `cos`, `tan`, `log`, `sqrt` .... etc. Would be easier to just wildcard. – Cory Kramer Nov 17 '14 at 18:19
-
1Sympy is a nice library. http://live.sympy.org/ Maybe a bit overkill for "8+3", but if you want to solve equations – el3ien Nov 17 '14 at 18:22
-
1
-
1To be fair, if we're gonna talk about best practices, we should mention to not *ever* use `eval` before worrying about wildcard imports. – Max Noel Nov 17 '14 at 18:24
0
I would use regex to pull out the number(s), and then do a check to see what operation to preform on said number(s).

Freelancer
- 86
- 1
- 9