I would do it entirely without ToString
. The main tool in combining mixed type output in a given order is Row
:
Ns = 1;
Table[Row[
{
Ket[Row[{
Replace[
Quotient[i - 1, Ns], {0 -> "\[UpArrow] ",
1 -> "\[DownArrow] "}], Mod[i, Ns]}]
],
Bra[Row[{Replace[
Quotient[j - 1, Ns], {0 -> "\[UpArrow] ",
1 -> "\[DownArrow] "}], Mod[j, Ns]}]
]}],
{i, 1, Ns*2}, {j, 1, Ns*2}] // MatrixForm
$\left(
\begin{array}{cc}
|\text{$\uparrow $ }0\rangle
\langle \text{$\uparrow $ }0| &
|\text{$\uparrow $ }0\rangle
\langle \text{$\downarrow $ }0|
\\
|\text{$\downarrow $ }0\rangle
\langle \text{$\uparrow $ }0| &
|\text{$\downarrow $ }0\rangle
\langle \text{$\downarrow $ }0|
\\
\end{array}
\right)$
Edit to elaborate on comment
In the long run, it may be better to separate the formatting from the algebra. To that end, I would first observe that there is an algebraic reason for the order of the bra and ket to be maintained. You're really forming something that in a matrix representation corresponds to non-commutative multiplication. So it makes sense to enter these bras and kets with a specially defined multiplication symbol, say, \[CenterDot]
-- the $\cdot$ symbol. This symbol has no pre-defined meaning and allows you to tailor any output format for it that you like. That is, you input a "multiplication" with $\cdot$ but we can set it up to output the product without explicit multiplication symbol. Moreover, if the labels of the kets and bras are always a spin arrow and a number, you can predefine that in a Format
statement too:
arrows = {0 -> "\[UpArrow]", 1 -> "\[DownArrow]"};
Format[Ket[x_, y_]] := Ket@Row[{x /. arrows, "\[ThinSpace]", y}];
Format[Bra[x_, y_]] := Bra@Row[{x /. arrows, "\[ThinSpace]", y}];
Format[CenterDot[x__]] := Row[Riffle[{x}, "\[ThinSpace]"]];
Ns = 1;
Table[
Ket[
Quotient[i - 1, Ns], Mod[i, Ns]
]\[CenterDot]Bra[
Quotient[j - 1, Ns], Mod[j, Ns]
],
{i, 1, Ns*2}, {j, 1, Ns*2}] // MatrixForm
The point here is that where it says \[CenterDot]
in the code, I actually only had to enter the shortcut Esc.
Esc. So the ordered product is now very easy to enter, and the actual algebraic expression is much easier to read.
I again used Row
for formatting, combined with \[ThinSpace]
as a spacer between elements of the bras and kets, as well as in the product.