11
$\begingroup$

How to programmatically convert an operator such as Equilibrium into its displayed form as a string? The conversion should work like this:

FullForm[convert /@ {Equilibrium, LongRightArrow, LeftVector, Equal}]

Mathematica graphics

I've tried various methods with no avail:

  • converting to strings and wrapping in "\[...]"
  • using different form wrappers (DisplayForm, TraditionalForm, etc.)
  • using low level boxes, but since that is really not my alley, I was a bit clueless
  • since operators with built-in meaning are used too, argument usage does not seem viable (e.g. ToString[Equal["", ""]] which returns True)
$\endgroup$
  • 2
    $\begingroup$ Don't be confused by Mma interpretation of Unicode chars. Try ToCharacterCode@ToString@Equilibrium["a", "a"] and them FromCharacterCode@% // FullForm $\endgroup$ – Dr. belisarius Mar 28 '12 at 13:27
12
$\begingroup$

This seems to work

convert[str_] := Module[{stream, output},
  stream = StringToStream["\"\\[" <> ToString[str] <> "]\""];
  output = Read[stream];
  Close[stream];
  output]

convert /@ {Equilibrium, LongRightArrow, LeftVector, Equal} // InputForm

Mathematica graphics

Edit

You could also do something like this:

convert[str_] := ToExpression["\"\\[" <> ToString[str] <> "]\""]

convert /@ {Equilibrium, LongRightArrow, LeftVector, Equal} // InputForm
$\endgroup$
10
$\begingroup$

How about (updated based on TomD's comment):

convert = StringTrim@ToString[HoldForm@#["", " "]]&

then,

In[]:= convert/@{Equilibrium,LongRightArrow,LeftVector,Equilibrium}
Out[]= {\[Equilibrium],\[LongRightArrow],\[LeftVector],\[Equilibrium]}

Note, that the output here is a string:

In[]:= Head/@%
Out[]= {String,String,String,String}

Mathematica graphics

Edit Note, this also works on operators like Plus or Minus.

$\endgroup$
  • $\begingroup$ Nice solution, and almost perfect: the Equal sign (it is now correctly present in my original post) that is returned is the two-character format (==) instead of the one-character version (see my updated Q). This difference can be a probelem if you simplify the solution to this: StringTake[ToString[HoldForm@str["", ""]], {2}], as it clips the == sign to =. $\endgroup$ – István Zachar Mar 28 '12 at 13:42
  • $\begingroup$ That's a good point. Let me see what I can figure out. $\endgroup$ – Eli Lansey Mar 28 '12 at 14:28
  • $\begingroup$ Nice solution. A slight modification with StringTrim. For example StringTrim@ToString@HoldForm@#["", ""] & /@ {Equilibrium, LongRightArrow, Equal, SameQ, Plus}. $\endgroup$ – user1066 Mar 28 '12 at 16:26
  • $\begingroup$ @TomD Good point. Forgot about that function. Still stuck on that double-equals, though. Seems like Heike's second solution might work better. $\endgroup$ – Eli Lansey Mar 28 '12 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.