CodeBlanks Logo Icon CodeBlanks

find and index

Learn searching with find and index.

find and index

find returns the first position of a substring; if not found, it returns -1:

"hello".find("l")   # 2
"hello".find("x")   # -1

index does the same but raises ValueError if not found. So find is safer.

Both return the index of the first match; to find later matches, use the start parameter.

Searching with find

The second parameter of find is the start position:

s = "hello"
s.find("l")        # 2
s.find("l", 3)     # 3

This is used to find the next match. With a loop you can find all match positions.

This method is very useful for searching log files.

Practice Find a position with find

Assign "hello world" to text. Assign text.find("world") to pos. Then print print(pos).

Starter code

main.py
# Find a position with find

Sample solution

main.py
text = "hello world"
pos = text.find("world")
print(pos)

Expected output

6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match find and index

Term Meaning
find Returns -1 if missing
index Raises ValueError if missing
first match Return position
start parameter Next match

2 Complete the find call

Question
pos = "hello".____("l")
Answer
pos = "hello".find("l")

Explanation: find("l") gives the position of 'l'.

3 What does "hello".find("x") return?

  • -1 Correct answer
  • Raises an error
  • None
  • 0

Explanation: find returns -1 when not found.

All lessons in Beginner