Lets say I have a string "1*5/6*(7+8)"
. I need to evaluate this string without eval. How should I go about doing it?
Asked
Active
Viewed 1,933 times
0

The6thSense
- 8,103
- 8
- 31
- 65

Savinay Narendra
- 75
- 12
-
2[Shunting-yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm) – Kevin Aug 28 '15 at 11:59
-
4@luoluo, is that a joke? – Padraic Cunningham Aug 28 '15 at 12:03
-
2@luoluo: 'eval' is evil. – Sven Marnach Aug 28 '15 at 12:03
-
1Have you attempted to solve this problem? If you have, please edit your question to include your code and research to show what hasn't worked for you. If you haven't, you should attempt to solve it yourself first and then post the code and research here. It makes your question easier for others to answer too! – SuperBiasedMan Aug 28 '15 at 12:04
-
I attempted it but it became a bit complex. So I was asking for a better solution. – Savinay Narendra Aug 28 '15 at 12:05
-
What about `ast.literal_eval` ? – Avinash Raj Aug 28 '15 at 12:07
-
1@AvinashRaj, that will not work – Padraic Cunningham Aug 28 '15 at 12:07
1 Answers
1
If it's not a problem for you to have sympy
as dependency, you can use sympy.sympify
.
>>> from sympy import sympify
>>> sympify("1*5/6*(7+8)").evalf()
12.5000000000000

beezz
- 2,398
- 19
- 15
-
Sympify also uses "eval" is not safe to use in potentially dangerous enviroments – j4n7 Jan 17 '22 at 17:59