Python String rindex() Method
rindex() returns the last occurrence of the substring str in the string, an exception will be thrown if there is no matching string, you can specify the optional parameter [beg:end] to set the search interval.
Python String rindex() Syntax
rindex() method syntax.
str.rindex(str, beg=0 end=len(string))
Python String rindex() Parameters
- str – the string to look for
- beg – the position to start the search, default is 0
- end – the end position of the search, the default is the length of the string.
Python String rindex() Return Value
Returns the last occurrence of the substring str in the string, an exception is thrown if there is no matching string.
Python String rindex() Example#1
The following example shows the use of the rindex() function (with a start or end index). If we provide start and end values to check a string, Python string rindex() will search only within that range.
#!/usr/bin/python3
string = "apis apis"
print(string.rindex("apis", 0, 4))
print(string.rindex("apis", 0, -5))
string = "101001010"
# since there are no '101' substring after string[0:3], thus it will take the last occurrence of '101'
print(string.rindex('101', 2))
Output:
Python String rindex() Example#2
The following example demonstrates that the rindex() function has no start and end indexes.
#!/usr/bin/python3
string = "apis apis"
print(string.rindex("apis"))
string = "demos"
print(string.rindex('e'))
Output:
Python String rindex() Example#3
When the parameter string is not found in the target string, the error ValueError is generated.
#!/usr/bin/python3
text = 'api for demos'
result = text.rindex('xxxxx')
print("Substring 'xxxxx':", result)
Output: