How to get a string as a mathematical formula in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to get a string as a mathematical formula in Python?

How can I get a string and have the program read it as a mathematical formula in Python? E.g., get "x²+2x+1" as a mathematical formula.

7th May 2020, 6:54 AM
Leo Arteaga
4 Answers
+ 2
Thanks, but how do I do that? Is there a string method that would get the job done? I've tried with .index, .find, and .split. I haven't used Python but I have tu use it for the final project of my programming class.
7th May 2020, 7:05 AM
Leo Arteaga
+ 2
A formula of this kind "x²+2x+1" can not been executed directly. The correct spelling should be: "x**2+2*x+1". So you can see that 'x²' has to be replaced by x**2, and 2x has to be replaced by '2*x'. If you have defined x in your code, you can finally execute the reworked input string with eval() function. Not forget to say, that eval() can execute most kind of instructions, which makes your system vulnerable against attacks. If you want to make the adaption from a mathemathical expression to a valid python expression in a coding, you need to parse the originla expression correctly, which is not a trivial task.
7th May 2020, 9:25 AM
Lothar
Lothar - avatar
+ 1
Thanks! I'll trt it.
7th May 2020, 7:10 AM
Leo Arteaga
+ 1
Okay. Thank you very much!
7th May 2020, 4:54 PM
Leo Arteaga