I am trying to take a piece of user input: 5+5
or 5*5
but my code receives it as a string. I want to convert it to an expression from which an answer can be deduced. However, I am not sure how to do this.
Asked
Active
Viewed 195 times
1

Yash Sharma
- 78
- 1
- 11
2 Answers
1
For that there's a standard function called as eval
.
Examples:
>>> eval("5*5")
25
>>> eval("5+5")
10
>>> eval("2+3*4-4")
10
It will take a string and then calculate the output as per the BODMAS Rule.

Keshav Biyani
- 235
- 1
- 10
-
But if the user input is untrusted, [`eval` is dangerous](/a/9558001/4518341). – wjandrea Oct 30 '21 at 17:48
-
Is there any way to avoid that? – Yash Sharma Oct 30 '21 at 17:49
-
Oh is it ?? I wasn't aware. Let me read more. Thanks. – Keshav Biyani Oct 30 '21 at 17:50
-
2@Yash To avoid the danger? Yeah, the [linked duplicate](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) has some solutions. – wjandrea Oct 30 '21 at 17:51
-
Yes, I think if the user enters a malicious piece of code then something bad could happen to my computer or application. – Yash Sharma Oct 30 '21 at 17:51
-
I think the linked duplicate should work. Thanks – Yash Sharma Oct 30 '21 at 17:52
-1
Simply use "eval", but unsafe.

Radek Rojík
- 104
- 5
-
This isn't very informative. How do you use `eval`? Why is it unsafe? – wjandrea Oct 30 '21 at 17:49