2

It seems that Mathematica reserves the capital i, I, for the imaginary unit. I have the following expression:

expr = a.b + II

For the user, I want to display the above expression with just I (for readability, it represents the inertia tensor). So I do:

Print[ToString[ReplaceAll[expr, II -> I] // TraditionalForm]]

But I still get the "imaginary unit" and not an actual capital i:

enter image description here

How do I display a capital i? Thanks! To emphasize: this is just to display to the user in a string output, in the actual code I use II...

MarcoB
  • 67,153
  • 18
  • 91
  • 189
space_voyager
  • 841
  • 4
  • 11

3 Answers3

6

To achieve customized display forms, you use either Format or MakeBoxes. Converting to string is usually a measure of last resort, and not what I would recommend here.

Instead, just do this:

expr = a.b + II

(* ==> II + a.b *)

II /: MakeBoxes[II, StandardForm] := RowBox[{"I"}]

expr = a.b + II

(* ==> I + a.b *)

Edit: TraditionalForm, String output

In MakeBoxes, the second argument can also be a blank pattern to allow the output I not only in StandardForm, as I did above:

II /: MakeBoxes[II, _] := RowBox[{"I"}]

Then, you can for example get this somewhat prettier output:

TraditionalForm[a.b + II]

$a.b+I$

or also this string representation, if desired:

ToString[a.b + II, TraditionalForm]

$\tt a.b+I$

Jens
  • 97,245
  • 7
  • 213
  • 499
4
expr = a.b + II;
II2I[n_] := StringReplace[ToString[n], "II" -> "I"];
II2I[expr]
3

Since you are only doing this for printing then you can simply replace II with "I"

Print[ToString[ReplaceAll[expr, II -> "I"] // TraditionalForm]]
(* a.b + I *)
Edmund
  • 42,267
  • 3
  • 51
  • 143