Start learning free

LESSON 66 OF 673 · STRINGS I

String Find in Python

Lesson

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