Re: Combining elements of a list
- To: mathgroup at smc.vnet.net
- Subject: [mg108851] Re: Combining elements of a list
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Sun, 4 Apr 2010 07:44:23 -0400 (EDT)
On 4/3/10 at 6:09 AM, ebaugh at illinois.edu wrote: >How could I go from: {h,e,l,l,o} to {hello}? In[1]:= StringJoin @@ {"h", "e", "l", "l", "o"} Out[1]= hello which is short hand for: In[2]:= Apply[StringJoin, {"h", "e", "l", "l", "o"}] Out[2]= hello >That is the first step of what I am really looking to do. Which is >to go from: {{t,h,i,s},{i,s},{a},{t,e,s,t},{m,e,s,s,a,g,e}} to "this >is a test message" The sublists can be made into strings as follows: In[3]:= StringJoin @@@ {{"t", "h", "i", "s"}, {"i", "s"}, {"a"}, {"t", "e", "s", "t"}, {"m", "e", "s", "s", "a", "g", "e"}} Out[3]= {this,is,a,test,message} which is short hand for In[4]:= Apply[StringJoin, {{"t", "h", "i", "s"}, {"i", "s"}, {"a"}, {"t", "e", "s", "t"}, {"m", "e", "s", "s", "a", "g", "e"}}, {1}] Out[4]= {this,is,a,test,message} But since no space characters are present, you cannot simply do Apply[StringJoin,... here. First, you need to add the space characters, then join the strings. One way to do that would be: In[5]:= StringDrop[ Apply[StringJoin, StringJoin @@@ (Flatten[{" ", #}] & /@ {{"t", "h", "i", "s"}, {"i", "s"}, {"a"}, {"t", "e", "s", "t"}, {"m", "e", "s", "s", "a", "g", "e"}})], 1] Out[5]= this is a test message Here, I added a space character in front of each sublist. Then I converted the sublists to strings using StringJoin@@@. Next, I combined the strings to a single string using Apply[StringJoin,...]. Finally, I deleted the extraneous leading space with StringDrop[..., 1]