Equation parsing in Python

WalkingRandomly picture WalkingRandomly · Feb 27, 2009 · Viewed 53.7k times · Source

How can I (easily) take a string such as "sin(x)*x^2" which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of x?

Answer

S.Lott picture S.Lott · Feb 27, 2009

Python's own internal compiler can parse this, if you use Python notation.

If your change the notation slightly, you'll be happier.

import compiler
eq= "sin(x)*x**2"
ast= compiler.parse( eq )

You get an abstract syntax tree that you can work with.