How do I go from {C,4,G,5,S,7}
to C4G5S7
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"
ToExpression@StringJoin@(ToString /@ {C, 4, G, 5, S, 7})
(* C4G5S7 *)
-
-
$\begingroup$ @Mr.Wizard, the usual reason: that it didn't occur to me:) $\endgroup$– kglrFeb 28, 2013 at 8:45
-
$\begingroup$ Actually now that I think about it in this simple construct my objection to
ToExpression
is probably meaningless. Never mind, and +1. $\endgroup$ Feb 28, 2013 at 8:51 -
$\begingroup$ @Mr.Wizard,
Symbol
is 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 :) $\endgroup$– kglrFeb 28, 2013 at 9:08 -
$\begingroup$ 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). $\endgroup$ Feb 28, 2013 at 9: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 (