Search code examples
sympysymbolic-math

Replace "a**b" to pow(a,b)


For example, I have the following code:

import sympy as sp
t = sp.Symbol("t")
f = t**2
print(f)

Output: t**2

Can I get output pow(t,2), using sympy?

Thank you.


Solution

  • you could try to hack the string printer:

    from sympy.printing import StrPrinter
    StrPrinter._print_Pow = lambda self, expr: "pow(%s, %s)" % (self._print(expr.base), self._print(expr.exp))
    

    That is, this overwrites the method _print_Pow in the class StrPrinter, which is responsible for printing the string form of Pow objects.