Python Function Reference

str.rfind

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

Python 3.13
str.rfind(sub[, start[, end]])
  • [ ]optional part
sub
The substring to find.
str
start
The index to start searching from, 0 by default; a negative one counts from the end.
intOptional
end
The index before which the search stops, the end by default; a negative one counts from the end.
intOptional

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