How to convert expression with Subscript to string
how to convert a expression containing 2D format into corresponding string that retains the format programmatically? For example, how to convert
{a^b + 1, 1.23*10^2, 2 Subscript[a, b]} (* Please Press Ctrl+Shift+N to convert it to standard form *)
to
{"\!\(\*SuperscriptBox[\(a\), \(b\)]\)+1", "1.23\[Times]\!\(\*SuperscriptBox[\(10\), \(2\ \)]\)", "2\!\(\*SubscriptBox[\(a\), \(b\)]\)"}
The easiest way is to prevent evaluation of the expressions what can be done with Unevaluated
and HoldAll
. First, define the function
toString = Function[expr, ToString[Unevaluated@expr, StandardForm], HoldAll];
Now you can simply apply this function to an expression:
You can Map
it over the list for obtaining separate string for every expression in the list:
Or you can make this function Listable
and it will thread over the lists automatically:
toString = Function[expr, ToString[Unevaluated@expr, StandardForm], {HoldAll, Listable}];
Obtaining the box form from FullForm[ToBoxes["t1"]]
(that's t subscript 1) - the box form can be used in a function like so:-
make[x_, n_] :=
ToExpression[
StringJoin["\"\\!\\(\\*SubscriptBox[\\(", ToString[x], "\\), \\(",
ToString[n], "\\)]\\)\""]]
make[t, 1]
make[t, 1] == "t1" (* again, t subscript 1 *)
True
To convert a subscripted variable another function can be used:-
f[x_] := Module[{a, b},
a = x[[1]];
b = x[[2]];
make[a, b]]
f[t1]
"t1"
To convert an expression such as the following more manipulations will be needed.
expr = s + Subscript[t, 1] + u (* Hold can be used to preserve the order *)
s + u + t1
The problem is a matter of manipulating the output from this ...
ToBoxes[expr]
RowBox[{"s", "+", "u", "+", SubscriptBox["t", "1"]}]
... to the output here:
ToBoxes["s+u+t1"] (* expr with t subscript 1 pasted into quotes*)
(* "\"s+u+\\!\\(\\*SubscriptBox[\\(t\\), \\(1\\)]\\)\"" *)
For this example the manipulation can be done like so:
z = ToBoxes[expr];
ToExpression[
StringJoin["\"",
First[z] /. SubscriptBox[a_, b_] :>
StringJoin["\\!\\(\\*SubscriptBox[\\(", a, "\\), \\(", b, "\\)]\\)"],
"\""]]
"s+u+t1"
The output here includes t subscript 1.