简体   繁体   中英

How do I use the enumerate function for CodeHS 8.4.13: Owls, Part 2?

This is what I'm supposed to do:

This program is an extension of your previous 'Owls' program. You can find your previous program here!

In addition to just reporting how many words contained the word owl, you should report the indices at which the words occurred!

Here's what an example run of your program might look like:

 Enter some text: Owls are so cool! I think snowy owls might be my favorite. Or maybe spotted owls.

There were 3 words that contained "owl". They occurred at indices: [0, 7, 15] As you can see from the output, you'll have to use another list to store the indices where you found the words containing “owl”.

The enumerate function might also come in handy!

This is my code right now:

text = input("Enter some text: ")
text.lower()
text.split()
print "There are " + str(text.count("owl")) + " words that contained \"owl\"."
print "They occured at indices: for c, value in enumerate(text, 1):
    print(c, value)

I have absolutely no idea how to use the enumerate function. The way that I am using the enumerate function right now is something that I got from some other website. When I try to run this code, the first thing that I get is this error:

Error: Line 5
ParseError: bad token on line 5

From this, I know that the way I am using enumerate is wrong. However, I do not know the right way to use it.

In this line here:

print "They occured at indices: for c, value in enumerate(text, 1):
    print(c, value)

You have not ended the string with " so Python keeps reading more and more, assuming there is still more to this string, until it reaches the end of your file. You don't want this, as the part: for c, value in enumerate(text, 1): is a command you want Python to do, it is not itself a string you want Python to print. So first we close your string:

print "They occured at indices: "
for c, value in enumerate(text, 1):
    print(c, value)

This should get rid of your error, but will print the wrong answers. You have another issue in the line: text.split() where you do not understand just how split() works. I'll leave researching that part up to you.

text = input("Enter some text: ")
text.lower()
text.split()
print "There are " + str(text.count("owl")) + " words that contained \"owl\"."
print "They occured at indices: for c, value in enumerate(text, 1):"
print "They occured at indices: "
for c, value in enumerate(text, 1):
print(c, value)

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