Python rfind() Method: Find Last Occurrence of Substring
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
The given code demonstrates the usage of Python's built-in rfind() method to locate the last occurrence of a specific substring within a string. The string "Hello, welcome to my world." is assigned to the variable txt, and txt.rfind("e") searches for the last index where the letter 'e' appears.
Unlike the find() method which searches from the beginning, rfind() scans the string from right to left. If the substring is not found, it returns -1. This makes it ideal for tasks like extracting file extensions, locating the last occurrence of a delimiter, or analyzing text from the end.
Key points:
- Returns an integer index (zero-based).
- Optional
startandendparameters allow a limited search range. - Use
find()for left-to-right search. - If the substring is absent, the return value is
-1.