Start learning free

LESSON 65 OF 344 · STRINGS I

String Find in Python: find(), index() and Searching Text

Lesson Read the full explanation

In Python, you can find the index of a substring using find():

s.find(sub)         # returns index of first occurrence, or -1 if not found
s.index(sub)        # like find(), but raises ValueError if not found
s.find(sub, start)  # search starting from index `start`

Here are some examples:

sentence = "Hello World"
idx = sentence.find("World")
print(idx)  # 6

print(sentence.find("xyz"))  # -1  (not found)

The index returned is the position of the first character of the found substring.


Assignment
Follow the Coding Tutorial and find the index of "World" in sentence!


Hint
Use sentence.find("World") and assign the result to idx.

STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · STRINGS I

    String Find in Python, explained

    What find() does

    A string is a sequence of characters, and each character has a position, called an index, counted from 0. The find() method searches a string for a smaller piece of text, called a substring, and tells you where it starts. It is the tool to reach for when you need the position of something inside a string, for example to cut the string at that point.

    sentence = "Hello World"
    print(sentence.find("World"))  # 6
    print(sentence.find("xyz"))    # -1
    

    The result is the index of the first character of the match. In "Hello World" the letters H e l l o take indices 0 to 4, the space is at 5, and the W of "World" is at 6. When the substring does not occur, find() returns -1, which can never be a real position.

    The related methods and arguments

    Searching from a later position

    A second argument tells find() where to start looking. The index it returns still counts from the beginning of the whole string:

    s = "Hello World"
    print(s.find("o"))     # 4
    print(s.find("o", 5))  # 7
    print(s.find("o", 8))  # -1
    

    The first "o" is at index 4. Starting at index 5 skips it and finds the one inside "World" at index 7. Starting at index 8 leaves no "o" to find.

    find() versus index()

    The index() method works the same way but reacts to a missing substring differently. Instead of returning -1 it raises an error:

    s = "Hello World"
    try:
        s.index("xyz")
    except ValueError as e:
        print("ValueError:", e)
    
    ValueError: substring not found
    

    Use find() when "not found" is a normal outcome you want to handle with an if. Use index() when a missing substring would be a bug and you want the program to stop loudly.

    Other useful relatives

    • rfind() searches from the right, so it returns the position of the last occurrence: "Hello World".rfind("o") is 7.
    • count() returns how many times a substring occurs: "Hello World".count("o") is 2.
    • The in operator answers a plain yes or no: "World" in "Hello World" is True. If you do not need the position, in is the simpler choice.

    Gotchas

    • Case matters. "Hello World".find("world") returns -1, because lowercase w is a different character from W. Lower both strings first if you want a case-insensitive search.
    • Only the first match is reported. find() returns one index. To locate the next occurrence, search again with a start argument just after the previous match.
    • Do not use the result as a condition. Writing if s.find("H"): looks reasonable, but the match is at index 0, and 0 counts as false, while the not-found value -1 counts as true. Compare explicitly: if s.find("H") != -1:, or use in.
    • The empty string is always found. s.find("") returns 0.
    • Negative results are not indices. A returned -1 must be checked before you use it to slice or index. Python would accept sentence[-1], but it would give you the last character, not an error.

    The exercise, step by step

    The lesson gives you a variable sentence containing "Hello World" and asks for the index where "World" begins.

    1. Pick the method. You want a position, and the lesson expects the value -1 rather than an error if the text were missing, so the method is find.
    2. Call it on sentence. Write sentence.find("World"), passing the text to search for as a string.
    3. Store the answer in idx. Assign the call to a new variable of that name, below the existing line.
    sentence = "Hello World"
    
    idx = sentence.find("World")
    

    The variable idx now holds 6. You can check that it points at the right place by using it to index the string or to slice it:

    print(idx)               # 6
    print(sentence[idx])     # W
    print(sentence[idx:])    # World
    

    Key takeaways

    • s.find(sub) returns the index of the first occurrence of sub, or -1 when it is absent.
    • s.find(sub, start) begins searching at start, and the result is still an index into the whole string.
    • s.index(sub) behaves the same, but raises ValueError when the substring is missing.
    • Searches are case sensitive.
    • Compare the result with -1 instead of treating it as true or false.
    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free