Need to create a program that prints out words starting with a particular letter

别说谁变了你拦得住时间么 提交于 2019-12-24 18:22:57

问题


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: AMD
Enter text: Advanced Micro Devices is a brand for all microsoft desktops
word: Advanced Micro Devices
word: all microsoft desktops

it's pretty simple. I'm new and having trouble figuring out how...my code is currently...

ipt1 = raw_input("Three letters: ") ## Asks for three letters
ipt2 = raw_input("Text: ") ## Asks for text
ipt1_split = ipt1.split() ## Converts three letters to list
ipt2_split = ipt2.split() ## Converts text to list

I'm not sure if you need a list or not, anyone know how to tackle this problem? Thanks!


回答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.



回答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.




回答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)])


来源:https://stackoverflow.com/questions/12298698/need-to-create-a-program-that-prints-out-words-starting-with-a-particular-letter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!