Fix the Bug -- find() vs index()
Beginner · Fix the bug · from Every Python String Method Explained with Examples
From the lesson: Every Python String Method Explained with Examples
Strings in Python come with a toolbox of built-in methods. These methods let you change case, remove extra spaces, search for words, split text apart, and much more.
Read the lessonThis code tries to find the position of "Python" in a sentence. It works when the word exists, but crashes when it doesn't.
Fix the code so it:
"Word not found" when the word is missingExpected output:
Found at position 7
Word not foundHint: The bug is that index() crashes when the word is missing. Which method returns -1 instead of crashing?
sentence = "I love Python programming"
# Find "Python" -- this line works fine
pos = sentence.index("Python")
print(f"Found at position {pos}")
# Find "Java" -- this line crashes!
pos = sentence.index("Java")
if pos >= 0:
print(f"Found at position {pos}")
else:
print("Word not found")
More string methods exercises
- Clean Up User InputBeginner
- Count Word OccurrencesBeginner
- Replace All OccurrencesBeginner
- Split a CSV LineBeginner
- Validate a UsernameBeginner
All Python exercises · 50 practice problems · Python Fundamentals quiz