Skip to main content

How to convert expression to String, but keep it looking similar to input form?


I have lots of differential equations, that I save to file (along with output and other things), as "strings", to process later in Latex and make a document of them.


I save each input differential equation, by first converting it from expression to String, then write it to the file (using WriteString command).


The problem is that when converting say eq = y'[x] == 1/y[x] to String, using ToString it becomes


Mathematica graphics


Which ofcource does not work, when saved to file, since it messes up the lines in the text file. So I use InputForm like this ToString[eq,InputForm] and now it works, the string is flat and on one line:


Mathematica graphics



The above is a string, and I can use that with no problem.


What I like however is to have the string look like the original expression, since it is easier to read (these will later show as verbatim in Latex), i.e. I need to convert expression to


   y'[x] == 1/y[x] 

to same as above, but as string


   "y'[x] == 1/y[x]"

I do not use 2D math at all in my input. All my original Mathematica expressions are flat, read from plain text file, read them, and process them, then need to save them back as strings with other things for post-processing.


But I'd like to keep the same looking expression used, but as string.


Question: How to to convert y'[x] == 1/y[x] to string "y'[x] == 1/y[x]" ?



For example of one Latex output, here is a link to help explain what I mean.


Mathematica 11.0.1.


Update:


To answer comments, I have the ODE's in a list. Then I use a loop to process them. Here is a MWE, a very simplified version. The process is completely non-interactive.


SetDirectory[NotebookDirectory[]];
lst = {{y'[x] == a*f[x]}, {y'[x] == x + Sin[x] + y[x]}, {y'[x] ==
x^2 + 3*Cosh[x] + 2*y[x]}};
fileName = "result.txt";
file = OpenWrite[fileName, PageWidth -> Infinity];
Do[

s = ToString[First@lst[[n]], InputForm];
WriteString[file, s];
WriteString[file, "\n"]
, {n, 1, Length@lst}
];
Close[file]

The text file where these are saved to now looks like


Mathematica graphics



Answer




My approach for this sort of thing is to define conditioned Format rules for the problematic symbols, and then to Block the condition true when using ToString. In addition, I like to use SequenceForm as a substitute for HoldForm. In your example, I would do:


Format[Derivative[n_?Positive][f_], InputForm] /; $Nasser :=
SequenceForm[f, OutputForm@StringJoin[ConstantArray["'", n]]]

Then, I would define a special tostring function:


SetAttributes[tostring, HoldFirst]
tostring[expr_] := Internal`InheritedBlock[{$Nasser = True, SequenceForm},
SetAttributes[SequenceForm, HoldFirst];
ToString[SequenceForm[expr], InputForm]
]


A couple examples:


tostring[y'[x] == a/y[x]] // InputForm
(* "y'[x] == a/y[x]" *)

tostring[x''[t] + c0 x'[t]^2 + c1 x[t]] // InputForm
(* "x''[t] + c0*x'[t]^2 + c1*x[t]" *)

Comments