Search code examples
pythonmathlatex

Converting a Python numeric expression to LaTeX


I need to convert strings with valid Python syntax such as:

'1+2**(x+y)'

and get the equivalent LaTeX:

$1+2^{x+y}$

I have tried SymPy's latex function but it processes actual expression, rather than the string form of it:

>>> latex(1+2**(x+y))
'$1 + 2^{x + y}$'
>>> latex('1+2**(x+y)')
'$1+2**(x+y)$'

but to even do this, it requires x and y to be declared as type "symbols".

I want something more straightforward, preferably doable with the parser from the compiler module.

>>> compiler.parse('1+2**(x+y)')
Module(None, Stmt([Discard(Add((Const(1), Power((Const(2), Add((Name('x'), Name('y'))))))))]))

Last but not least, the why: I need to generate those LaTeX snippets so that I can show them in a webpage with MathJax.


Solution

  • You can use sympy.latex with eval:

    s = "1+2**(x+y)"
    sympy.latex(eval(s))   # prints '$1 + {2}^{x + y}$'
    

    You still have to declare the variables as symbols, but if this is really a problem, it's much easier to write a parser to do this than to parse everything and generate the latex from scratch.