6

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

FortranForm[1I]

(0,1)

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.

sqrt6
  • 63
  • 3

1 Answers1

4

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

ClearAll[format] ;
format[rules_][expression_] := FixedPoint[
    StringReplace[rules], 
    ToString[FortranForm[expression]]
] ;

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

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

I.M.
  • 2,926
  • 1
  • 13
  • 18