Sub topic 3
Finding where a substring occurs
This chapter assumes you know Python variables, function calls, string indexing and slicing, and simple if and while statements. The previous chapter used in to ask whether text is present. Here you will ask where it is.
The four methods
Python has four string methods that return a position. Each returns the index of the first character of a match.
| Method | Searches from | If not found |
|---|---|---|
| `find` | the left | returns `-1` |
| `rfind` | the right | returns `-1` |
| `index` | the left | raises `ValueError` |
| `rindex` | the right | raises `ValueError` |
s = "Hello, World"
print(s.find("o")) # 4
print(s.rfind("o")) # 8
print(s.find("xyz")) # -1find reports the leftmost match, and rfind reports the rightmost. Both return an index counted from the start of the string, so the result works directly with slicing.
Limiting the search with start and end
All four methods accept optional start and end arguments. They work like slice bounds: the search covers start up to, but not including, end.
s = "Hello, World"
print(s.find("o", 5)) # 8
print(s.find("o", 0, 4)) # -1, because s[0:4] is "Hell"The returned index is still relative to the whole string, not to the slice. This lets you search again from just past a previous match.
Handling the not-found case
Choose the method by how you want a missing substring to behave.
- Use
findwhen absence is a normal outcome and you will check for it. - Use
indexwhen absence means something is wrong and you want the program to fail loudly.
s = "Hello, World"
try:
s.index("xyz")
except ValueError:
print("not found")The same trap applies if you use the result as an index without checking it. s[s.find("x")] silently reads the last character when find returns -1.
Finding every occurrence
find returns only the first match, so a loop with a moving start collects the rest.
text = "banana"
pos = text.find("an")
while pos != -1:
print(pos)
pos = text.find("an", pos + 1)
# 1
# 3Starting the next search at pos + 1 allows overlapping matches. Use pos + len("an") instead to skip past each match, which matches the non-overlapping rule that count uses.
Using the position
A position is most useful with slicing. This example splits an address at the @ sign, and rfind finds the last dot of a file name.
email = "[email protected]"
at = email.find("@")
if at != -1:
print(email[:at]) # ana
print(email[at + 1:]) # example.com
name = "archive.tar.gz"
dot = name.rfind(".")
print(name[dot + 1:]) # gzIf you only need to split once at a separator, partition (covered later) is often simpler than find plus slicing.
Common errors
- Testing
if s.find(x):instead of!= -1. - Forgetting that
indexraisesValueErrorand leaving it unhandled. - Treating the returned index as relative to the
startargument. It is always relative to the full string. - Expecting
findto take a pattern. It matches literal text only.
Exercise
What does "a.b.c".rfind(".") return, and what does "a.b.c".find(".", 2) return?
Show answer
rfind returns 3, the index of the last dot. find(".", 2) starts at index 2 and returns 3 as well, because the first dot at index 1 is skipped. Both indexes are relative to the whole string.