
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Last Occurrence of Substring in Python
In Python, working with strings is a common task in data processing and text analysis. The common operation is finding the last occurrence of a specific substring. It is useful in situations like extracting the domain names or locating the repeated elements in logs.
Python provides several methods to accomplish this; the most commonly used are ?
- Python rfind() Method
- Python rindex() Method
Using python rfind() Method
The Python rfind() method is used to find the last occurrence of the substring in the given string; if not found, it returns -1.
Syntax
string.rfind(value, start, end)
Example
Let's look at the following example, where we will consider the basic usage of the rfind().
str1 = "Welcome to tutorialspoint" index = str1.rfind("t") print("The last index of t in the given string is", index)
Output
The output of the above given example is:
The last index of t in the given string is 24
Uisng python rindex() Method
The Python rindex() method is used to find the last occurrence of a substring in a given string.
This method is similar to the rfind() method, but the difference is that the rfind() method returns -1, if the substring is not found, but the rindex() method raises an exception (Value Error).
Syntax
str.rindex(value, start, end)
Example 1
Consider the following example, where we are going to use the rindex() to find the last occurrence.
str1 = "Welcome to tutorialspoint" index = str1.rindex('t') print("The last index of t in the given string is",index)
Output
The output of the above example is as follows ?
The last index of t in the given string is 24
Example 2
In the following example, we are going to use rindex() and find the last occurrence of the substring that is not present in the original string and observe the output.
str1 = "Welcome to tutorialspoint" index = str1.rindex('d') print("The last index of t in the given string is",index)
Output
If we run the above program, it will generate the following output ?
Traceback (most recent call last): File "/home/cg/root/67f5acf8d76df/main.py", line 2, in <module> index = str1.rindex('d') ^^^^^^^^^^^^^^^^ ValueError: substring not found