rindex()
的语法是
str.rindex(sub[, start[, end]] )
rindex() 参数
rindex()
方法接受三个参数
- sub - 要在 str 字符串中搜索的子字符串。
- start 和 end(可选)- 子字符串在
str[start:end]
范围内搜索
rindex() 的返回值
- 如果字符串中存在子字符串,它将返回字符串中子字符串的最高索引。
- 如果字符串中不存在子字符串,它将引发 ValueError 异常。
rindex()
方法与字符串的 rfind() 方法类似。
唯一的区别是,如果未找到子字符串,rfind() 返回 -1,而 rindex() 会抛出异常。
示例 1:不带 start 和 end 参数的 rindex()
quote = 'Let it be, let it be, let it be'
result = quote.rindex('let it')
print("Substring 'let it':", result)
result = quote.rindex('small')
print("Substring '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'
# Substring is searched in ' small things with great love'
print(quote.rindex('t', 2))
# Substring is searched in 'll things with'
print(quote.rindex('th', 6, 20))
# Substring is searched in '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
另请阅读