描述
Python rindex() 方法返回子字符串最后一次出現在字符串中的索引位置,該方法與 rfind() 方法一樣,只不過如果子字符串不在字符串中會報一個異常。
語法
rindex() 方法語法:
S.rindex(sub[,start=0[,end=len(S)]])
參數
- sub -- 指定檢索的子字符串
- S -- 父字符串
- start -- 可選參數,開始查找的位置,默認為0。(可單獨指定)
- end -- 可選參數,結束查找位置,默認為字符串的長度。(不能單獨指定)
返回值
返回子字符串最后一次出現在字符串中的的索引位置,如果沒有匹配項則會報一個異常。
實例
以下實例展示了 rindex() 方法的使用方法:
#!/usr/bin/python3 S1 = "this is really a string example....wow!!!" S2 = "is" print (S1.rindex(S2)) print (S1.rindex(S2,10))
以上實例輸出結果如下:
5 Traceback (most recent call last): File "test.py", line 6, in <module> print (str1.rindex(str2,10)) ValueError: substring not found