Python Forum

Full Version: Trying to get the first letter of every word in a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to take out the first letter of every word in a list. It is not working. I believe the fault to be on line 9 but i can't figure out why.

def initialise(userText):
    lst = []
    firstLetters = []
    for i in userText:
        lst.append(i)
    firstLetters.append(lst[0])
    for x in lst:
        if x == " ":
            position = lst.index(x) + 1
            firstLetters.append(lst[position])
    userText = ''.join(firstLetters)
    return userText


text = input("Enter text: ")
print(initialise(text))
Isin't the objective to get first letter of every word in a string? If this is the case then simple 'split on space and get first letter' comprehension would do:

>>> text = 'Life, Universe and Everything'
>>> ''.join(word[0] for word in text.split())
'LUaE'
Getting back to the original post question, index() will not work because you can have repeating letters. You could use enumerate to iterate through the user text.
def initialise(userText):
    firstLetters = userText[0]
    for index, letter in enumerate(userText):
        if letter == " ":
            firstLetters += userText[index+1]
    return firstLetters
A problem with this approach is it assumes the next letter after a space is the start of a word. This fails for us older folks who follow a period with two spaces, and it would crash if you entered a trailing space.

A safer solution is to set a flag to let you know that you are in a break and looking for the start of the next word.
def initialise(userText):
    punctuation = ' .,:;()"'
    firstLetters = ''
    start = True
    for letter in userText:
        if letter in punctuation:
            start = True
        elif start:
            firstLetters += letter
            start = False
    return firstLetters
 
print(initialise('This is a test.  It works for (some) punctuaton.'))