How to display elements of a product in a certain order [duplicate]

This question already has an answer here:

I have several product states, represented by a string of variables - for example, "ABC". I'd like to multiply this state by a constant, call it J, to which I don't want to pre-assign a value. Using J * "ABC" as my input, the output returns: ABC J. How do I get Mathematica to display the output as J ABC instead?

Thanks a lot! :)

marked as duplicate by user9660, RunnyKine, m_goldberg, ilian, JensMar 22 '16 at 20:43

• ToString@Unevaluated[J *"ABC" ], maybe – user1066 Mar 21 '16 at 12:25

You can use NonCommutativeMultiply instead, since it does not have the Orderless attribute:

J ** ABC
• Can you expand on this answer? – RunnyKine Mar 21 '16 at 10:03

Input

sample = "ABC";
data = "J";
data <> " " <> sample

Output

"J ABC"

Reference

I don't recommend using Strings that you append to to represent objects. Use instead a sequence of the names wrapped inside a custom Head, something like

state[a, b, c]

and can add to the state via Prepend, Append, or most generally Insert depending on where you want to add the new state:

Append[state[a, b, c], j]
(* state[a, b, c, j] *)
Prepend[state[a, b, c], j]
(* state[j, a, b, c] *)
Insert[state[a, b, c], j, 2]
(* state[a, j, b, c] *)

Alternatively,

SetAttributes[state, Flat]
state[state[a, b, c], d]
state[d, state[a, b, c]]
(* state[a, b, c, d] *)
(* state[d, a, b, c] *)