Python Reference ยท String Methods
Python str.find() method
Reference for Python str.find(): get the lowest index of a substring or -1, use start and end bounds, and avoid the classic if-find-is-truthy bug.
The str.find() method searches a string for a substring and returns the index of the first (lowest) match. If the substring does not occur, it returns -1 instead of raising an error.
Because -1 is a valid-looking number, it is easy to misuse the result. If you only need to know whether a substring is present, use the in operator. If you want an exception when it is missing, use index().
print("banana".find("na")) # 2 print("banana".find("x")) # -1
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.find(sub) str.find(sub, start) str.find(sub, start, end)
| Name | Description |
|---|---|
sub |
The substring to look for. Must be a str. |
start |
Optional. Index where the search begins (default 0). |
end |
Optional. Index where the search stops, exclusive (default len(s)). |
Return value: the lowest index at which sub starts inside s[start:end], counted from the start of s (not from start), or -1 if there is no match.
Raises: TypeError if sub is not a string.
Usage notes
- Check against
-1explicitly.if s.find(x):is wrong twice: a match at index 0 is falsy and a miss (-1) is truthy. Writeif s.find(x) != -1:or, better,if x in s:. - Index is relative to the whole string, even when you pass
start. The loop above relies on that. - Empty substring.
s.find("")returns0(orstart, when it fits in the string). - Case-sensitive. Lower-case both sides for a caseless search, or use
re.searchwithre.IGNORECASE. - Last occurrence:
rfind()searches from the right.count()tells you how many matches exist. - Splitting at a delimiter is usually cleaner with
partition()orsplit()than withfind()and slicing. - Only for strings. Lists have
index()but nofind().