Python 字符串 rindex() 方法
rindex()
的语法是:
str.rindex(sub[, start[, end]] )
rindex() 参数
rindex()
方法接受三个参数:
- sub - 要在 str 字符串中搜索的子字符串。
- start 和 end(可选)- 子字符串在
str[start:end]
中被搜索。
rindex() 的返回值
- 如果字符串内存在子字符串,则返回字符串中子字符串最高索引。
- 如果字符串内不存在子字符串,则引发 ValueError 异常。
rindex()
方法类似于 字符串的 rfind() 方法。
唯一的区别是 rfind() 如果未找到子字符串则返回 -1,而 rindex() 会抛出异常。
示例 1:rindex() 没有 start 和 end 参数
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)
输出
子字符串 'let it': 22
Traceback (most recent call last):
File "...", line 6, in <module>
result = quote.rindex('small')
ValueError: 子字符串未找到
注意: 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: 子字符串未找到