Hey all!

I'm new to programming so please be patient if my question is obvious or listed somewhere else (I've looked!)

I want to be able to enter a sentence, split the sentence into septate words and then take the first letter of each word to create a new string. So that:
"the brown fox"
returns:
"tbf"

So far all I can do is split the sentence into the separate words:

import string
def main():
    print "This program splits the words in a sentence"
    print
    p = raw_input("Enter a sentence: ")
    words = string.split(p)
    print "The split words are:", words
    
main()

Thanks for any help!

I give you two versions so that you can compare them

def firstLettersA(theString):
    theWords = theString.split()
    theLetters = mapl(lamda w: w[:1], theWords)
    theResult = ''.join(theLetters)
    print theWords, theLetters, theResult
    return theResult

def firstLettersB(theString):
    return ''.join(map(lambda w: w[:1], theString.split()))

def main():
    print "This program splits the words in a sentence"
    print
    p = raw_input("Enter a sentence: ")
    print "The first letters are '%s'"  % firstLettersB(theString)

Here's one making use of list comprehension:

>>> def FirstLetters( s ):
...     return ''.join( [ lett[0] for lett in s.split() ] )
...     
>>> FirstLetters( 'My mother used to bake apple pies in the foo bar' )
'Mmutbapitfb'
>>>

If list comprehension or generator expressions are not in your knowledge yet, maybe this is a little easier to understand:

def first_letters(s):
    temp = ""
    for letter in s.split():
        temp += letter[0]
    return temp
    
s = 'Old hero sleeps healthy in Thailand'
print first_letters(s)

A little bit more long winded, but using only very basic concepts:

def first_letters2(s):
    space = " "
    s = space + s
    temp = ""
    for k in range(len(s)):
        if s[k] == space:
            temp += s[k+1]
    return temp

s = 'My mother used to bake apple pies in the foo bar'
print first_letters2(s)

Thanks for the help guys!

The one that made the most sense to me was the first_letters2 code.

Again, thanks all for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.