Python rfind() Method | Simple Tutorial
Python Basic Tutorials
- Python Basic Tutorial
- Python Introduction
- Python Environment Setup
- Python Chinese Encoding
- Python VS Code
- Python Basic Syntax
- Python Variable Types
- Python Operators
- Python Conditional Statement
- Python Loop Statements
- Python While Loop Statement
- Python for Loop Statement
- Python Nested Loops
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python Number (Numbers)
- Python Strings
- Python List
- Python Tuple
- Python Dictionary
- Python Date and Time
- Python Functions
- Python Modules
- Python File I/O
- Python File Methods
- Python Exception Handling
- Python OS File/Directory Methods
- Python Built-in Functions
Python Advanced Tutorials
- Python Object-Oriented Programming
- Python Regular Expressions
- Python CGI Programming
- Python MySQL
- Python Network Programming
- Python SMTP Sending Email
- Python Multithreading
- Python XML Parsing
- Python GUI Programming (Tkinter)
- Differences between Python 2.x and 3.x
- Python IDE
- Python JSON
- Python AI Drawing
- 100 Python Examples
- Python Quiz
Python rfind() Method
The rfind() method returns the highest index in the string where the substring is found, or -1 if not found.
Syntax
str.rfind(sub[, start[, end]])
Parameters
- sub: The substring to search for.
- start (optional): The starting position of the search.
- end (optional): The ending position of the search.
Return Value
Returns the highest index of the substring, or -1 if not found.
Example
text = "Hello, world! This is a test string."
index = text.rfind("test")
print(index) # Output: 21
If the substring is not found:
text = "Hello, world! This is a test string."
index = text.rfind("xyz")
print(index) # Output: -1
You can also specify a range to search within:
text = "Hello, world! This is a test string."
index = text.rfind("is", 10, 25)
print(index) # Output: 16
Note: Unlike find(), rfind() searches from right to left and returns the last occurrence of the substring.
YouTip