Need to create a program that prints out words sta

2019-08-28 04:39发布

问题:

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