Sub topic 3
Finding where a substring occurs
This chapter assumes you know basic Python syntax, string indexing and slicing, and how if statements and while loops work. It also assumes you have met the in operator, which answers "is this text present?". Here you will learn the methods that answer "where is it?": find, rfind, index, and rindex.
From "is it there?" to "where is it?"
The in operator returns a boolean. That is enough for a check, but it cannot help you cut out the text before or after a match. For that you need a position, which is an integer index into the string.
s = "Hello, World"
print("World" in s) # True
print(s.find("o")) # 4
print(s.find("o", 5)) # 8
print(s.find("xyz")) # -1
try:
s.index("xyz")
except ValueError:
print("not found")Both find and index return the index of the first character of the first match. They differ only when nothing matches. find returns -1, and index raises ValueError.
The four methods
| Method | Searches from | If missing |
|---|---|---|
| `find(sub[, start[, end]])` | the left | returns `-1` |
| `rfind(sub[, start[, end]])` | the right | returns `-1` |
| `index(sub[, start[, end]])` | the left | raises `ValueError` |
| `rindex(sub[, start[, end]])` | the right | raises `ValueError` |
The r versions return the start index of the last match, not the first. Searching from the right changes which match you get, but the returned index is always the position of the match's first character.
s = "Hello, World"
print(s.find("o")) # 4
print(s.rfind("o")) # 8
print(s.find("l")) # 2
print(s.rfind("l")) # 10All four methods take the substring as a str. They do not accept a tuple of alternatives the way startswith does. Passing a tuple raises TypeError. If you need "whichever of these comes first", you need a loop or the re module, covered in the last chapter.
Restricting the search with start and end
The optional start and end arguments work like slice bounds. The search covers s[start:end], so end is exclusive. The returned index is still relative to the whole string, not to the slice.
s = "banana"
print(s.find("an")) # 1
print(s.find("an", 2)) # 3
print(s.find("ana", 0, 3)) # -1
print(s.find("an", 0, 3)) # 1The third call returns -1 because the match must fit entirely inside the window. The window s[0:3] is "ban", and "ana" does not fit in it.
Negative values count from the end, as in slicing:
s = "banana"
print(s.find("a", -3)) # 3
print(s.rfind("a")) # 5
print(s.rfind("a", 0, 5)) # 3rfind("a", 0, 5) ignores the last character, so the last "a" it can see is at index 3.
The -1 trap
The most common error with find is treating its result as a boolean. The value -1 is truthy, and a valid match at index 0 is falsy. Both mistakes give the wrong answer:
s = "xyz"
if s.find("x"): # find returns 0, which is falsy
print("found x")
else:
print("x not found") # wrong: x is at the start
if s.find("q"): # find returns -1, which is truthy
print("found q") # wrong: q is absentAlways compare to -1 explicitly:
s = "xyz"
pos = s.find("q")
if pos != -1:
print("found at", pos)
else:
print("not found")A second trap is using the result as an index without checking it. -1 is a valid index, so no error occurs. You silently get the last character:
s = "xyz"
pos = s.find("q")
print(s[pos]) # z (pos is -1, so this is the last character)Choosing between find and index
Pick the method that matches what a missing substring means in your program.
- Use
findwhen absence is a normal case you will handle with a branch, such as an optional comment marker in a line. - Use
indexwhen absence means the input is malformed. TheValueErrorstops the program at the point of the problem, instead of letting a-1travel on and cause confusing results later.
index also works well inside a try block when several lookups must all succeed:
line = "name=Ada"
try:
eq = line.index("=")
except ValueError:
print("missing '=' in line")
else:
print(line[:eq], line[eq + 1:]) # name AdaFor splitting at a single separator, partition is often simpler than finding an index and slicing. The splitting section later in this tutorial covers it.
Finding every occurrence
A single call finds only one match. To collect all matches, call find in a loop, and start each search just after the previous match.
def find_all(text, sub):
positions = []
start = text.find(sub)
while start != -1:
positions.append(start)
start = text.find(sub, start + 1)
return positions
print(find_all("banana", "ana")) # [1, 3]
print(find_all("banana", "a")) # [1, 3, 5]
print(find_all("banana", "x")) # []Moving ahead by start + 1 finds overlapping matches. In "banana", the matches for "ana" begin at 1 and 3 and share the middle "a". If you want only non-overlapping matches, advance by len(sub) instead. That gives [1] for this example, which is also what count would report.
Searching backwards and from a position
rfind is the natural tool for "the last one". File extensions and the final path separator are typical uses:
path = "reports/2026/summary.final.txt"
slash = path.rfind("/")
dot = path.rfind(".")
print(path[slash + 1:]) # summary.final.txt
print(path[dot + 1:]) # txt
print(path[:slash]) # reports/2026If the path has no /, rfind returns -1, and slash + 1 becomes 0. The slice path[0:] is then the whole string. That is a lucky result, and it makes this idiom work for bare filenames too. Do not count on such luck for other cases.
You can also use start to pick up where an earlier search ended. This function extracts the text between two delimiters:
def between(text, left, right):
i = text.find(left)
if i == -1:
return None
i += len(left)
j = text.find(right, i)
if j == -1:
return None
return text[i:j]
print(between("<b>bold</b>", "<b>", "</b>")) # bold
print(between("no tags", "<b>", "</b>")) # NoneThe second search starts at i, so it cannot match a right delimiter that appears before the content begins. Without that argument, find(right) could return an earlier position and produce a wrong slice.
Edge cases
- Empty substring. The empty string matches everywhere.
"abc".find("")is0, and"abc".find("", 3)is3, the position just past the end."abc".find("", 4)is-1, because the start is beyond the string. - Case sensitivity. All four methods compare exactly.
"Hello".find("h")is-1. For case-insensitive work, normalize both sides first. A later chapter coverscasefoldfor this. - Positions after changes. Indexes refer to the string you searched. Because strings are immutable, any method that returns a new string gives you a new coordinate system. Do not reuse an index from the original on the modified copy.
- Speed. Each call scans from
start. A loop over all matches therefore touches each region about once, which is fine. Callingfindfrom the beginning in every iteration would repeat work.
Exercise
What does each of these print? s = "level"; print(s.find("l"), s.rfind("l"), s.find("l", 1), s.find("e", 2, 4))
Show answer
It prints 0 4 4 3. find("l") finds the first "l" at index 0. rfind("l") finds the last one at index 4. find("l", 1) starts at index 1, so the next "l" is at 4. find("e", 2, 4) searches s[2:4], which is "ve", and finds "e" at index 3 in the full string.
Exercise
This function should return the text after the first colon, or an empty string if there is no colon. It has a bug. Find it and fix it. def after_colon(line): pos = line.find(":") return line[pos + 1:]
Show answer
When there is no colon, pos is -1, so pos + 1 is 0 and the function returns the whole line instead of an empty string. Fix it by checking for -1:
def after_colon(line):
pos = line.find(":")
if pos == -1:
return ""
return line[pos + 1:]
Exercise
Write count_overlapping(text, sub) that returns how many times sub occurs in text, counting overlapping matches, using find. What should count_overlapping("aaaa", "aa") return, and how does that differ from "aaaa".count("aa")?
Show answer
Loop with find, moving the start to start + 1 after each hit:
def countoverlapping(text, sub):
n = 0
start = text.find(sub)
while start != -1:
n += 1
start = text.find(sub, start + 1)
return n
`countoverlapping("aaaa", "aa") returns 3 (matches at 0, 1, and 2). The built-in "aaaa".count("aa") returns 2, because count` skips overlapping matches.