Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Combining elements of a list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg108849] Re: Combining elements of a list
  • From: Helen Read <hpr at together.net>
  • Date: Sun, 4 Apr 2010 07:43:59 -0400 (EDT)
  • References: <hp7735$krb$1@smc.vnet.net>
  • Reply-to: HPR <read at math.uvm.edu>

On 4/3/2010 6:59 AM, ebaugh at illinois.edu wrote:
> How could I go from:
> {h,e,l,l,o}
> to
> {hello}?

If you intend to treat the letters as characters (as opposed to symbols 
or expressions), you should enter them as strings, i.e., enclose them in 
quotes. Use StringJoin to concatenate strings.

s1={"h","e","l","l","o"}

StringJoin[s1]

If you did not enter the characters as strings to begin with, you can 
convert them using ToString.

a1={h,e,l,l,o}

a2=Map[ToString,a1]

StringJoin[a2]

> 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"

How are you generating the lists to begin with? It would probably be a 
lot easier to work with strings to begin with, instead of lists. 
However, working with what you have, here is a way to do it. I'll do it 
one step a time so you can see what each step does, with some (* 
comments *).

b1 = {{t, h, i, s}, {i, s}, {a}, {t, e, s, t}, {m, e, s, s, a, g, e}}

b2 = Map[ToString, b1, {2}]

(* Map ToString accross b1 at the second level, to convert the letters 
to strings *)

b3 = Table[" ", {n, Length[b2] - 2}]

(* The Length of b2 is the number of words. We'll insert spaces in 
between words -- not on the ends -- so we need Length[b2] - 2 spaces. *)

b4 = Riffle[b2, b3]

(* riffle b2 and b3 to put the spaces in between the words *)

b5 = Flatten[b4]

(* remove the extra braces *)

StringJoin[b5]

(* concatenate the strings *)


-- 
Helen Read
University of Vermont


  • Prev by Date: Re: Combining elements of a list
  • Next by Date: Re: Combining elements of a list
  • Previous by thread: Re: Combining elements of a list
  • Next by thread: Re: Combining elements of a list