Python Forum
Trying to get the first letter of every word in a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to get the first letter of every word in a list
#3
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.'))
bowlofred likes this post
Reply


Messages In This Thread
RE: Trying to get the first letter of every word in a list - by deanhystad - Jan-05-2021, 05:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,563 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  find some word in text list file and a bit change to them RolanRoll 3 1,512 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,486 Aug-12-2021, 04:25 PM
Last Post: palladium
  Trying to find first 2 letter word in a list of words Oldman45 7 3,694 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 2,560 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  Python Speech recognition, word by word AceScottie 6 15,971 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  print a word after specific word search evilcode1 8 4,807 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  How do you replace a word after a match from a list of words in each line of a file? vijju56 1 3,446 Oct-17-2019, 03:04 PM
Last Post: baquerik
  returns index of list if contains a word zarize 0 1,815 Sep-09-2019, 09:29 AM
Last Post: zarize
  Score each word from list variable pythonias2019 6 3,343 Jun-13-2019, 05:44 PM
Last Post: gontajones

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020