简体   繁体   中英

How do I complete the 8.4.13 Owls, Part 2 problem in CodeHS Python?

So the assignment says:

In addition to just reporting how many words contained the word owl, you should report the indices at which the words occurred! Here's an example run of your program might look like:

Enter some text: Owls are so cool! I think snowy owls might be my faborite. Or maybe spotted owls.
There were 3 words that contained "owl".
They occurred at indices: [0, 7, 15]

This is what I have so far for my code:

sentence = input("Talk about something: ")
sentence.lower()

print "There are " + str(sentence.count("owls)) + " of the word \"owls\" in the sentence"
print "They occurred at indices: " + str(sentence.findl("owls")

But that only prints the first index it's found at, how do I get it to print all of the indexes it's found at?

sentence = 'Owls are so cool! I think snowy owls might be my faborite. Or maybe spotted owls.'
words = [i for i, word in enumerate(sentence.split(' ')) if 'owl' in word.lower()]

This works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM