如果子字符串,則rindex()方法返回字符串內子字符串的最高索引
被發現。否則會引發異常。
用法:
str.find(sub, start, end)
參數:
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.
注意:如果未提供開始索引和結束索引,則默認情況下它將0和length-1用作開始索引和結束索引,而我們的搜索中不包含結束索引。
返回:
Returns the highest index of the substring inside the string if substring is found. Otherwise it raises an exception.
例子:
input:text = 'geeks for geeks' result = text.rindex('geeks') output:10 input:text = 'geeks for geeks' result = text.rindex('ge') output:10
錯誤和異常:
ValueError:如果在目標字符串中找不到參數字符串,則會引發此錯誤。
代碼1
# Python code to demonstrate working of rindex()
text = 'geeks for geeks'
result = text.rindex('geeks')
print("Substring 'geeks':", result)
輸出:
Substring 'geeks':10
代碼2
# 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
# 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
相關用法
注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 String rindex() in python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。