6
$\begingroup$

How do I go from {C,4,G,5,S,7} to C4G5S7

$\endgroup$
1

3 Answers 3

10
$\begingroup$

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:

Mathematica graphics

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"
$\endgroup$
5
$\begingroup$
   ToExpression@StringJoin@(ToString /@ {C, 4, G, 5, S, 7})
   (* C4G5S7 *)
$\endgroup$
5
  • $\begingroup$ Any reason you don't use Symbol? $\endgroup$
    – Mr.Wizard
    Feb 28, 2013 at 8:36
  • $\begingroup$ @Mr.Wizard, the usual reason: that it didn't occur to me:) $\endgroup$
    – kglr
    Feb 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$
    – Mr.Wizard
    Feb 28, 2013 at 8:51
  • $\begingroup$ @Mr.Wizard, Symbol is already used in your answer, and, in combination with Row, makes a better answer than mine. Simon, if this were my question I would have accepted Mr.Wizard's answer :) $\endgroup$
    – kglr
    Feb 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$
    – Mr.Wizard
    Feb 28, 2013 at 9:11
0
$\begingroup$
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 (

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.