Python 的 str.rindex(~) 方法返回源字符串中最后一次出现的指定子字符串的索引。如果未找到子字符串,则会引发 ValueError 异常。
参数
1. sub | string
要在源字符串中搜索的子字符串。
2. start | number | optional
开始搜索的源字符串的索引(包括)。默认为 0 。
3. end | number | optional
结束搜索的源字符串的索引(不包括)。默认为 end=len(source string) 。
返回值
如果找到该子字符串,则返回该子字符串在源字符串中最后一次出现的索引。
如果未找到,则引发 ValueError 异常。
例子
基本用法
要获取最后一次出现 "bc" 的起始索引:
w = "abcdbc"
w.rindex("bc")
4
"abcdbc" 中最后一次出现的 "bc" 出现在索引位置 4(在 'd' 之后)。
ValueError
要获取最后一次出现 "gg" 的起始索引:
x = "abcdbc"
x.rindex("gg")
ValueError: substring not found
由于在"abcdbc"中找不到"gg",因此引发了ValueError。
启动参数
从索引2(含)开始搜索:
y = "abcdbc"
y.rindex("bc", 2)
4
结束参数
要停止在索引 3 处搜索(不包括):
z = "abcdbc"
z.rindex("bc", 0, 3)
1
由于搜索结束于索引位置 3 ( 'd' ),并且不包括索引位置 3 ( 'd' ),因此最后一次出现的 "bc" 位于索引 1 处。
相关用法
- Python String rindex()用法及代码示例
- Python String rstrip方法用法及代码示例
- Python String rsplit()用法及代码示例
- Python String rjust方法用法及代码示例
- Python String rpartition()用法及代码示例
- Python String rpartition方法用法及代码示例
- Python String replace()用法及代码示例
- Python String rjust()用法及代码示例
- Python String rstrip()用法及代码示例
- Python String rfind方法用法及代码示例
- Python String rsplit方法用法及代码示例
- Python String replace方法用法及代码示例
- Python String rfind()用法及代码示例
- Python String count方法用法及代码示例
- Python String isnumeric方法用法及代码示例
- Python String Center()用法及代码示例
- Python String zfill方法用法及代码示例
- Python String decode()用法及代码示例
- Python String count()用法及代码示例
- Python String join()用法及代码示例
- Python String casefold()用法及代码示例
- Python String isalnum()用法及代码示例
- Python String endswith方法用法及代码示例
- Python String isidentifier()用法及代码示例
- Python String startswith()用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Python String | rindex method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
