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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
