rindex()方法在字符串中搜索指定的值,并返回它被找到的最后位置。如果未找到子字符串,則會引發(fā)異常。
rindex()的語法為:
str.rindex(sub[, start[, end]] )
rindex()方法采用三個(gè)參數(shù):
sub -要在str字符串中搜索的子字符串。
start和end(可選)-在str[start:end]內(nèi)搜索子字符串
如果字符串中存在子字符串,則它將在找到子字符串的字符串中返回最后位置。
如果子字符串在字符串中不存在,則會引發(fā)ValueError異常。
rindex()方法類似于string的rfind()方法。
唯一的區(qū)別是,rfind() 如果未找到子字符串,則返回-1,而rindex()則會引發(fā)異常。
quote = 'Let it be, let it be, let it be'
result = quote.rindex('let it')
print("子字符串 'let it':", result)
result = quote.rindex('small')
print("子字符串 'small ':", result)運(yùn)行該程序時(shí),輸出為:
Substring 'let it': 22
Traceback (most recent call last):
File "...", line 6, in <module>
result = quote.rindex('small')
ValueError: substring not found注意: Python中的索引從0開始,而不是1。
quote = 'Do small things with great love'
# 搜索子字符串' small things with great love'
print(quote.rindex('t', 2))
# 搜索子字符串 'll things with'
print(quote.rindex('th', 6, 20))
# 搜索子字符串 'hings with great lov'
print(quote.rindex('o small ', 10, -1))運(yùn)行該程序時(shí),輸出為:
25
18
Traceback (most recent call last):
File "...", line 10, in <module>
print(quote.rindex('o small ', 10, -1))
ValueError: substring not found