Python字符串 rindex() 方法
如果找到子字符串, Python String rindex() 方法返回字符串内子字符串的最高索引。否则,它会引发异常。
Syntax:
str.rindex(sub, start, end)
Parameters:
- sub : It’s the substring which needs to be searched in the given string.
- start : Starting position where sub is needs to be checked within the string.
- end : Ending position where suffix is needs to be checked within the string.
Note: If start and end indexes are not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indexes is not included in our search.
Return:
Returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception.
Errors and Exceptions:
ValueError: This error is raised when the argument string is not found in the target string.
示例 1
input: text = 'geeks for geeks'
result = text.rindex('geeks')
output: 10
input: text = 'geeks for geeks'
result = text.rindex('ge')
output: 10
Python3
# Python code to demonstrate working of rindex()
text = 'geeks for geeks'
result = text.rindex('geeks')
print("Substring 'geeks':", result)
Python3
# Python code to demonstrate error by rindex()
text = 'geeks for geeks'
result = text.rindex('pawan')
print("Substring 'pawan':", result)
Python3
# Python code to demonstrate working of rindex()
# with range provided
quote = 'geeks for geeks'
# Substring is searched in ' geeks for geeks'
print(quote.rindex('ge', 2))
# Substring is searched in 0 to 10 range
print(quote.rindex('geeks', 0, 10))
输出:
Substring 'geeks': 10
示例 2
Python3
# Python code to demonstrate error by rindex()
text = 'geeks for geeks'
result = text.rindex('pawan')
print("Substring 'pawan':", result)
错误:
Traceback (most recent call last):
File "/home/dadc555d90806cae90a29998ea5d6266.py", line 6, in
result = text.rindex('pawan')
ValueError: substring not found
示例 3
Python3
# Python code to demonstrate working of rindex()
# with range provided
quote = 'geeks for geeks'
# Substring is searched in ' geeks for geeks'
print(quote.rindex('ge', 2))
# Substring is searched in 0 to 10 range
print(quote.rindex('geeks', 0, 10))
输出:
10
0