Editor

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 lesson

This 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:

  • Prints the position when the word is found
  • Prints "Word not found" when the word is missing
  • Expected output:

    Found at position 7
    Word not found

    Hint: 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

    All Python exercises · 50 practice problems · Python Fundamentals quiz