Python Function Reference

str.rfind

Find the last occurrence of the substring sub in the string.

Python 3.13
str.rfind(sub[, start[, end]])

Parameters

substr
The substring to find.
startintoptional
The index where the search starts.
endintoptional
The index before which the search stops.

Return value

The index of the last occurrence, or -1 if the substring is not found.

Examples

Position of the last slash

Python 3.13
print('a/b/c.txt'.rfind('/'))
3

File extension after the last dot

Python 3.13
name = 'archive.tar.gz'
print(name[name.rfind('.') + 1:])
gz

Details

If the substring is missing, it returns -1, so check for it before slicing: with -1, the slice name[name.rfind(".") + 1:] returns the whole string. To get an error instead of -1, use str.rindex.

See also