Question & Answer

7.4.15 Owls, Part 2

 

/* Your code... */
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)

1 Answer

Verified archive
Quizzma TeamJanuary 20, 2025

It looks like you’re trying to write a Python program that counts the occurrences of the word “owl” in user-inputted text and prints the indices where it occurs. However, there are a few errors in your code. Here’s a corrected version along with an explanation:


# Get user input

text = input("Enter some text: ")

# Convert text to lowercase

text_lower = text.lower()

# Split text into words

words = text_lower.split()

# Count occurrences of "owl"

count_owl = words.count("owl")

# Print count of "owl"

print("There are " + str(count_owl) + " words that contained 'owl'.")

# Print indices where "owl" occurs

print("They occurred at indices: ", end="")

# Use enumerate to find indices (1-based)

indices = [i + 1 for i, word in enumerate(words) if word == "owl"]

print(indices)

### Explanation:
1. Lowercase Conversion: The input text needs to be converted to lowercase so that the counting is case-insensitive.
2. Splitting the Text: We split the text into words using `.split()`.
3. Counting Occurrences: We count how many times “owl” appears with `.count(“owl”)`.
4. Finding Indices: We use `enumerate` to get the indices of each occurrence of “owl” in the list of words.
5. **