To find the index of the last occurrence of a substring in Python, you can use the rfind
method of the string object.
In this example,
str
with a string value.rfind
method of the string object to find the index of the last occurrence of a specific substring within str
.rfind
method returns the index of the last occurrence of the substring in the string.str = 'Hello World, Hello Python'
lastIndex = str.rfind('Hello')
print('Last index of substring is:', lastIndex)
Last index of substring is: 13
In this example,
str1
and str2
with different values.rfind
method of str1
to find the index of the last occurrence of str2
within str1
.rfind
method returns the index of the last occurrence of str2
in str1
.str1 = 'apple banana cherry banana'
str2 = 'banana'
lastIndex = str1.rfind(str2)
print('Last index of substring is:', lastIndex)
Last index of substring is: 20
In this tutorial, we learned How to find the Index of Last Occurrence of Substring in Python language with well detailed examples.