Meaning
Returns the highest index at which a substring is found within a string, searching from the end; returns -1 if not found. This avoids inefficient reverse scans or manual looping when you need the last occurrence. Use it when parsing file extensions, extracting basenames, or checking for trailing patterns.
Primary Function
String searching
Communicative Purpose
Find the last occurrence of a substring within a string.
Pattern
source_string.rfind(target_substring)
Core Structure
... .rfind(...)
Função primária
String searching
Propósito comunicativo
Find the last occurrence of a substring within a string.
Situações de gatilho
File processing: parsing file extensions; Path manipulation: extracting basenames from paths; Text processing: checking for trailing patterns
Contextos
Text processing, data cleaning, file path manipulation
Padrão
source_string.rfind(target_substring)
Estrutura central
... .rfind(...)
Slots de substituição
source_string: str, target_substring: str
Colocados típicos
- slicing operations
- conditional checks (result != -1)
- path manipulation
Substituições comuns
- str.find() for first occurrence
- str.rindex() which raises ValueError if not found
Erros comuns
Confusing rfind with find, assuming it returns None or raising an exception on not found, using the -1 result directly as a slice index without checking
Similar / contraste
str.find() finds first occurrence; str.rindex() raises ValueError if substring absent
Interferências
Coming from JavaScript: expecting -1 for not found → same behavior, returns -1; Coming from some languages where a similar function returns None → assuming None return leads to unexpected truthiness, check for -1 instead.
Família do chunk
- str.find
- str.index
- str.rindex
- str.rpartition
Nuance
The returned -1 is a valid index in Python when used in slicing (refers to the last character), so always test for -1 before slicing.
Efeito pragmático
Provides an efficient reverse search without needing to reverse the string.
Dica de memória
Think 'right find'.
Nota
The method scans from the end; O(n) time complexity. Returns -1 when substring absent, which is a valid slice index for the last character, so always test before slicing.
Upgrade path
s.rpartition(sub)[0] # gets substring before last occurrence
Log in to save chunks.