I am trying to convert some set of equations to a form that will be easy for Python to evaluate numerically, hence I am using Mathematica's FortranForm

My problem is that




whereas I want


I do not want


which results in


What I want is to be able to cast the DiagonalMatrix[equations] part of my expressions to the equivalent in Python - np.diag(equations), where I have imported numpy as np

Solution, but not the desired one

I found a way round my problem, though it is not what I want, but I will post it for people that my just care about the end result.

Use FortranForm["np.diag"] and then export the result to a text file. Then in Python one can read the file and rewrite it line by line, while stripping all the quotes using this piece of code

def fromMathematica(func):
    """" string -> string 

    Imports a file, created by Mathematica and reads it, so that it can be evaluated for specific values
    file = open('path' + func + .txt' , 'r+')
    lines = file.readlines()
    for line in lines:
        line = line.replace('"', '').strip()
    m = file.read()
    return m
  • $\begingroup$ You have to do some transformations manually. In this case, you might want to use StringReplace. $\endgroup$
    – Sumit
    Dec 15, 2016 at 10:34
  • $\begingroup$ I am not sure I see your point. My problem is that if it is a string, FortranForm will return it surrounded by quotes, which is what I want to avoid $\endgroup$ Dec 15, 2016 at 11:58
  • $\begingroup$ I think you are taking an ill-concieved approach trying to use mathematics dot product function to produce a name-scoping construct in python. Suggest name the function something like npdotdiag in mathematica and do a stringreplace on the result. (You should not need to do anything by hand! ) $\endgroup$
    – george2079
    Dec 15, 2016 at 12:58

2 Answers 2


Probably I don't understand your problem correctly, still giving it a try ..

ff = FortranForm[p + DiagonalMatrix[a + b]]

p + DiagonalMatrix(a + b)

StringReplace[ToString[ff], "DiagonalMatrix" -> "np.diag"]

p + np.diag(a + b)

  • $\begingroup$ This exactly solves my problem for the moment. I didn't think of replacing stuff after using FortranForm. I will see what happens when I try that approach on my pages long equations :) $\endgroup$ Dec 15, 2016 at 14:15

I would give DiagonalMatrix a custom FortranForm:

Format[DiagonalMatrix,FortranForm]=Format["np.diag", OutputForm];


ToString[p + DiagonalMatrix[a + b], FortranForm]

"p + np.diag(a + b)"


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.