
rindex()方法在字符串中搜索指定的值,并返回它被找到的最后位置。如果未找到子字符串,则会引发异常。
rindex()的语法为:
str.rindex(sub[, start[, end]] )
rindex()参数
rindex()方法采用三个参数:
- sub -要在str字符串中搜索的子字符串。 
- start和end(可选)-在str[start:end]内搜索子字符串 
rindex()返回值
- 如果字符串中存在子字符串,则它将在找到子字符串的字符串中返回最后位置。 
- 如果子字符串在字符串中不存在,则会引发ValueError异常。 
rindex()方法类似于string的rfind()方法。
唯一的区别是,rfind() 如果未找到子字符串,则返回-1,而rindex()则会引发异常。
示例1:没有start和end参数的rindex()
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)运行该程序时,输出为:
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。
示例2:带有start和end参数的rindex()
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))运行该程序时,输出为:
25
18
Traceback (most recent call last):
  File "...", line 10, in <module>
    print(quote.rindex('o small ', 10, -1))
ValueError: substring not found
                    
                