I'm trying to convert the output of WolframClient to Python. Here's a toy example:

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr

def get_session():
    session = WolframLanguageSession()
    session.evaluate(wlexpr('Range[5]')) #warmup
    return session

session = get_session()


((Rule[Global`a[0], Rational[5, 3]],),)

I'm hoping to instead get something simpler (a string is sufficient):

"a[0] = 5/3"


Ideally I'd like to port the output of mathematica to Sympy. I've tried Sympy's Mathematica parser, but it doesn't recognize any of the "non-whitelisted" expressions such as Rational[5,3]. I've tried using Mathematica's InputForm function but that doesn't seem to work.

  • $\begingroup$ You may make a PR to sympy's repo, and add the support to Rational. $\endgroup$ Commented Dec 31, 2020 at 8:12

1 Answer 1


One way to get the form you want is to apply ToString and StringForm. For this particular example, Numerator and Denominator are also used.

  sol = Values@First@Flatten@Solve[a[0] == 5/3, a[0]];
  ToString@StringForm["a[0] = `1`/`2`", Numerator[#], Denominator[#]] & @sol

(*  a[0] = 5/3  *)

Other forms can be obtained with ToString and StringJoin (<>)

  sol = N@Values@First@Flatten@Solve[a[0] == 5/3, a[0]];
  "a[0] = " <> ToString[sol] """))

(*  a[0] = 1.66667  *)

In either case the Python return type is str, as

retval = session.evaluate("""
  sol = N@Values@First@Flatten@Solve[a[0] == 5/3, a[0]];
  "a[0] = " <> ToString[sol] """)


(*  str  *)

If you want the Python return type to be float, just use N

retval = session.evaluate("""
  N@Values@First@Flatten@Solve[a[0] == 5/3, a[0]] """)


(*  float  *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.