The Python method rfind is utilized to locate a substring within a string, returning the highest index at which the substring occurs. This indicates that it provides the index of the rightmost occurrence of the specified substring within the string. If the substring is not present, it will return -1.
Syntax of Python rfind(str,beg=0,end=len(str))
It has the following syntax:
rfind(sub[, start[, end]])
Parameters
- sub: substring to be searched.
- start (optional): starting index to start searching.
- end (optional): end index where to search stopped.
Return
It returns either index of substring or -1.
Different Examples for Python String rfind Function
Let’s examine a few instances of the rfind method to grasp its capabilities more thoroughly.
Example 1
Let's consider a straightforward example to demonstrate the use of the rfind method. This method provides the highest index at which a specified substring can be found within a string.
# Python rfind() method example
# Variable declaration
str = "Learn Python from C# Tutorial"
# calling function
str2 = str.rfind("Python")
# displaying result
print(str2)
Output:
Example 2
Here is another illustration to grasp the functionality of the rfind method.
# Python rfind() method example
# Variable declaration
str = "It is technical tutorial"
# calling function
str2 = str.rfind("t")
# displaying result
print(str2)
Output:
Example 3
This function accepts a total of three parameters, two of which are optional. We will specify the starting and ending indices for the function.
# Python rfind() method example
# Variable declaration
str = "It is technical tutorial"
# calling function
str2 = str.rfind("t",5) # Only starting index is passed
# displaying result
print(str2)
str2 = str.rfind("t",5,10) # Start and End both indexes are passed
print(str2)
Output: