acronym program

Ian Clark iclark at mail.ewu.edu
Fri Sep 21 17:38:07 CEST 2007


Shawn Minisall wrote:
> I'm trying to write a program that gets the first letter of every word 
> of a phrase and prints it on screen.  I'm having problems with it.  I'm 
> thinking a for loop would be good since I don't know the exact number of 
> words the user is going to enter, but after that I get confused.  How do 
> I tell python to just goto the beg of each word in the phrase and 
> include it in the acronym?  Am I on the right track?
> 
>     for a in string.split(phrase)
>     acronym = phrase [0]
>     acronym = acronym + 1
> 
> thx

List comprehensions[1] to the rescue!

     >>> phrase = 'hello there i am well how are you?'
     >>> acronym = [word[0] for word in phrase.split()]
     >>> acronym
     ['h', 't', 'i', 'a', 'w', 'h', 'a', 'y']

Ian

[1] http://docs.python.org/tut/node7.html#SECTION007140000000000000000




More information about the Python-list mailing list