0

I want to be able convert the input of a mathematical expression from a user to the python format for math expressions. For example if the user input is:

3x^2+5

I want to be able to convert that into

3*x**2+5

so that I can user this expression in other functions. Is there any existing library that can accomplish this in Python?

Daniel Rodríguez
  • 684
  • 3
  • 7
  • 15
  • 2
    [SymPy](http://docs.sympy.org/dev/modules/parsing.html) maybe? – Delgan Aug 18 '16 at 16:09
  • 1
    Why do you need a library? How many things do you need to translate? There aren't any real "non-standard" arithmetic symbols except for your example here, right? – Two-Bit Alchemist Aug 18 '16 at 16:10
  • I just want to be able to translate any mathematical expression from the user input, and that its parenthesis and symbols are correctly assigned. – Daniel Rodríguez Aug 18 '16 at 16:12
  • 1
    I faced something similar... I just taught everyone who used the system to enter equations in valid Python. – RoadieRich Aug 18 '16 at 16:18
  • There are some libraries that parse certain specific syntaxes. No idea which one you want to use though, your single example hardly scratches the surface of expression parsing... – Bakuriu Aug 18 '16 at 16:26

1 Answers1

1

You can use simple string formatting to accomplish this.

import re

expression = "3x^2+5"

expression = expression.replace("^", "**")
expression = re.sub(r"(\d+)([a-z])", r"\1*\2", expression)

For more advanced parsing and symbolic mathematics in general, check out SymPy's parse_expr.

2Cubed
  • 3,401
  • 7
  • 23
  • 40