search
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.rfind(sub[, start[, end]]) Parameters
| Parameter | Purpose |
|---|---|
| sub | substring to search for |
| start | optional slice start (default 0) |
| end | optional slice end (default len(str)) |
Examples
>>> 'abcabc'.rfind('b')
4 finds the rightmost occurrence
>>> 'file.tar.gz'.rfind('.')
8 commonly used to split at the last delimiter
>>> 'hello'.rfind('z')
-1 returns -1 when not found
>>> 'aaa'.rfind('a', 0, 2)
1 end index is exclusive, like slicing
Gotcha
Returns -1 on miss (never raises). Consider str.rpartition() when you need the tail slice as well as the position.
Related methods
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.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.partition
Splits the string at the first occurrence of sep and returns a 3-tuple (before, sep, after). If sep is not found, returns (original, '', '') — so unpacking is always safe.
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.