I am trying to use the Mathematica output of a complicated expression as input for python. As suggested in this answer, the FortranForm of an expression already comes close. However, the FortranForm of the complex number 1i is



which would be a tuple in python and not a complex number. How do I convert these expressions to complex numbers? In Python, 1i would be 1j. I don't know if this is possible directly. Alternatively, complex numbers can be generated by calling the constructor complex(a, b), where a is the real part and b is the imaginary part.


1 Answer 1


You can use StringExpression to match (x, y) patterns:

ClearAll[format] ;
format[rules_][expression_] := FixedPoint[
] ;

rules = {
    " " -> "",
    "+-" -> "-",
    "(" ~~ A:NumberString ~~ "," ~~ B:NumberString ~~ ")" :> StringTemplate["(`A`+`B`j)"][<|"A" -> A, "B" -> B|>]
} ;

expression = 1I + (2 + 3I) x + (3.1 - 0.1I)/x^2;
(* "(0+1j)+(3.1-0.1j)/x**2+(2+3j)*x" *)

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.