search
str.find
Returns the lowest index in the string where substring sub is found within the slice [start:end]. Returns -1 if the substring is not found, unlike index() which raises ValueError.
str.find(sub[, start[, end]]) Parameters
| Parameter | Purpose |
|---|---|
| sub | substring to search for |
| start | optional slice start index (default 0) |
| end | optional slice end index (default len(str)) |
Examples
>>> 'hello world'.find('world')
6 returns index of first match
>>> 'hello'.find('z')
-1 returns -1 when substring is missing (no exception)
>>> 'ababab'.find('a', 2)
2 start argument narrows search window
>>> 'abc'.find('')
0 empty substring is found at position 0
Gotcha
Returns -1 on miss (never raises). Use the `in` operator for a simple membership check — it is clearer and faster than `find(...) != -1`.
Related methods
str.rfind
Returns the highest index in the string where substring sub is found within [start:end]. Returns -1 if the substring is not found.
str.index
Like find(), but raises ValueError if the substring is not found. Use when the substring is expected to exist and its absence is an error.
str.count
Returns the number of non-overlapping occurrences of substring sub in [start:end]. Overlapping matches are not counted.
str.startswith
Returns True if the string starts with the given prefix, otherwise False. prefix may also be a tuple of strings to test against multiple candidates.
str.endswith
Returns True if the string ends with the given suffix, otherwise False. suffix may be a tuple of strings to test multiple candidates at once.