Python String rfind()
Python String.rfind() method returns the index of last occurrence of specified value in given string. The search for given value in this string happens from end to the beginning of the string, i.e., from right to left.
If the search value is not present in this string, rfind() returns -1
.
In this tutorial, we will learn the syntax and examples for rfind() method of String class.
Syntax
The syntax of String rfind() method in Python is
str.rfind(value, start, end)
where
Parameter | Required / Optional | Description |
---|---|---|
value | Required | A string. Index of this value in the string has to be returned. |
start | Optional | An integer. Specifies the index bound for search on the left side of string. |
end | Optional | An integer. Specifies the index bound for search on the right side of string. |
Examples
rfind() with default values
In this example, we will take a string 'abcd-abcd-abcd'
, and find the index of the value 'bc'
in the string.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
result = x.rfind(value)
print("Index :", result)
Output
Index : 12
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 11 12 13
c d : index of 'cd' is 12
The index of last occurrence of value is 12.
Even though there are multiple occurrences of the value in this string, rfind() method returns the index of last occurrence only.
rfind() with Specific Start
In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
start = 5
result = x.rfind(value, start)
print("Index :", result)
Output
Index : 12
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 11 12 13
|
start=5 from this position
c d : index of 'cd' is 12
rfind() with Specific Start and End
In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen and the end position up until which the search for value in the string has to happen.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
start = 5
end = 7
result = x.rfind(value, start, end)
print("Index :", result)
Output
Index : -1
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 11 12 13
| |
start=5 end=7
There is no occurrence of the value in this string for given start and end values.
Conclusion
In this Python Tutorial, we learned how to find the index of last occurrence of specified value in given string, using String method – rfind().