Skip to content Skip to sidebar Skip to footer

Need To Create A Program That Prints Out Words Starting With A Particular Letter

I need a program that asks the user for 3 letters then asks the user for a string, then prints out all words in the string that start with the three letters...e.g Enter 3 letters:

Solution 1:

Some hints:

  • To test if a string starts with another, you can use string.startswith().
  • Your first input does not need to be split, a string is a sequence.

Solution 2:

I'd do something like this:

letters = raw_input("letters: ").lower()
n = len(letters)
words = raw_input("text: ").split()
words_lc = [x.lower() for x in words] #lowercase copy for case-insensitive check

for x in range(len(words) - n + 1):
    if all((words_lc[x+n].startswith(letters[n]) for n in range(n))):
        print "match: ", ' '.join(words[x:x+n])

In this case the number of letters is dynamic, if you want it fixed to three just set n to three. If you want to match case of the letters, remove the lower calls on the raw_input and the comparison in all.


Solution 3:

Try this:

letters = "AMD"
text = "Advanced Micro Devices is a brand for all microsoft desktops"
words = text.split()
for i in xrange(len(words)-len(letters)+1):
    if "".join(map(lambda x: x[0], words[i:i+len(letters)])).lower() == letters.lower():
        print "word:", ".join(words[i:i+len(letters)])

Post a Comment for "Need To Create A Program That Prints Out Words Starting With A Particular Letter"