Re: Combining elements of a list
- To: mathgroup at smc.vnet.net
- Subject: [mg108850] Re: Combining elements of a list
- From: Murray Eisenberg <murray at math.umass.edu>
- Date: Sun, 4 Apr 2010 07:44:11 -0400 (EDT)
I'm going to assume you don't really have symbols (t, h, etc.) but rather one-letter strings ("t", "h", etc.) here. The basic function you want is StringJoin. Thus: StringJoin[{"t", "h", "i", "s"}] this Next, you have your list of lists: lis = {{"t", "h", "i", "s"}, {"i", "s"}, {"a"}, {"t", "e", "s", "t"}}; (I left out the last word.) So Map the function StringJoin onto that at level 1: Map[StringJoin, lis, 1] {"this", "is", "a", "test"} Now you need to append a blank to each word (except the last). For a single string str StringInsert[str," ",-1] does it, as in: trial=StringInsert["this"," ",-1] this (* you can't see the trailing blank here, so... *) StringLength[trial] 5 (You could also use StringJoin instead of StringInsert.) Now Map that function of appending a blank onto the list of words: appended = Map[StringInsert[#, " ", -1] &, words] {this ,is ,a ,test } Same thing, abbreviated: StringInsert[#, " ", -1] & /@ words Finally, join all the individual (blank-trailed) words into a single string and delete the final trailing blank: StringTrim@StringJoin[appended] Obviously, all those steps could be combined, encapsulated into a single function: sentenceFromLetters[lis_] := StringTrim@ StringJoin[StringInsert[#, " ", -1] & /@ Map[StringJoin, lis, 1]] Doubtless there are terser, or at least alternative ways, to do this using pattern-matching for at least some of the steps. If your original list really consisted of lists of symbols rather than lists of one-character strings, you could first convert that to a list of lists of one-character strings by using ToString. On 4/3/2010 7:09 AM, ebaugh at illinois.edu wrote: > How could I go from: > {h,e,l,l,o} > to > {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" > > Thanks all, > Jason Ebaugh > > > -- Murray Eisenberg murray at math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305