How do I go from {C,4,G,5,S,7} to C4G5S7
-
Related: http://mathematica.stackexchange.com/q/7063/121 – Mr.Wizard Feb 28 '13 at 08:51
3 Answers
If no elements of that list have values assigned:
Symbol @ ToString @ Row @ {C, 4, G, 5, S, 7}
C4G5S7
If values are assigned add HoldForm, and if making a function add attribute HoldAll:
SetAttributes[merge, HoldAll]
merge[expr_List] := Symbol @ ToString @ HoldForm @ Row @ expr
G=1; S=2;
{C, 4, G, 5, S, 7} // merge
C4G5S7
If one wants strings instead of symbols just leave out Symbol.
This method relies upon the particular behavior of formatting wrappers, Forms and how ToString handles them.
Row and HoldForm both act as wrappers for an expression. HoldForm additionally holds its arguments. Observe using InputForm (yet another wrapper) that both heads remain in the output:
HoldForm @ Row @ {1 + 1, 2 + 2} // InputForm
HoldForm[Row[{1 + 1, 2 + 2}]]
However, in StandardForm (output in a Notebook) or OutputForm (output for terminals and text formats) these wrappers are not printed. In the FrontEnd they affect the BoxData that is ultimately displayed.
As the documentation states:

Therefore ToString @ HoldForm[Row[{1 + 1, 2 + 2}]] yields:
"1 + 12 + 2"
And ToString[HoldForm[Row[{1 + 1, 2 + 2}]], StandardForm] yields:
"1+12+2"
- 271,378
- 34
- 587
- 1,371
ToExpression@StringJoin@(ToString /@ {C, 4, G, 5, S, 7})
(* C4G5S7 *)
- 394,356
- 18
- 477
- 896
-
-
-
Actually now that I think about it in this simple construct my objection to
ToExpressionis probably meaningless. Never mind, and +1. – Mr.Wizard Feb 28 '13 at 08:51 -
@Mr.Wizard,
Symbolis already used in your answer, and, in combination withRow, makes a better answer than mine. Simon, if this were my question I would have accepted Mr.Wizard's answer :) – kglr Feb 28 '13 at 09:08 -
Yours however is a straightforward and easy to understand approach, whereas mine relies upon the "weird" behavior of formatting wrappers (which I should probably remark upon, come to think of it). – Mr.Wizard Feb 28 '13 at 09:11
StringReplace[ToString[#], Except[WordCharacter] :> ""] & /@ {{C, 4,
G, 5, S, 7}, {2, A, 4, B, 6, C, 0}, {0, A, 1, B, 2.1, 0}}
=> {C4G5S7, 2A4B6C0, 0A1B210}
or
StringReplace[# /. b_ :> ToString[b],
Except[WordCharacter] :> ""] &@{C, 4, G, 5, S, 7}
=> C4G5S7
Notice that the first position of the list may be zero (
- 17,923
- 3
- 31
- 49