find and index
- Python course
- Beginner
- Lesson 91/116
- 4 min
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") # -1index 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) # 3This 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
# Find a position with findSample solution
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
pos = "hello".____("l")
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.