index()方法:
描述
Python index() 方法檢測字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結束) 范圍,則檢查是否包含在指定范圍內,該方法與 python find()方法一樣,只不過如果str不在 string中會報一個異常。
語法
index()方法語法:
S.index(str, beg=0, end=len(string))
參數
- S -- 父字符串
-
str -- 指定檢索的字符串
-
beg -- 開始索引,默認為0。
-
end -- 結束索引,默認為字符串的長度。
返回值
如果包含子字符串返回開始的索引值,否則拋出異常。
rindex()方法:
描述
Python rindex() 方法返回子字符串最后一次出現在字符串中的索引位置,該方法與 rfind() 方法一樣,只不過如果子字符串不在字符串中會報一個異常。
語法
rindex() 方法語法:
S.rindex(str, beg=0, end=len(string))
參數
-
str-- 指定檢索的子字符串
-
S -- 父字符串
-
start -- 可選參數,開始查找的位置,默認為0。(可單獨指定)
-
end -- 可選參數,結束查找位置,默認為字符串的長度。(不能單獨指定)
返回值
返回子字符串最后一次出現在字符串中的的索引位置,如果沒有匹配項則會報一個異常。
>>>S = 'love python!' >>>S.index('ove') 1 >>>S.sindex('ove', 2) AttributeError Traceback (most recent call last) <ipython-input-3-fef65cd971bb> in <module>() ----> 1 S.sindex('ove', 2) AttributeError: 'str' object has no attribute 'sindex' >>>S.index('ove', 1) 1 >>>S.index('ove', 1, 4) 1 >>>S.index('ove', 1, 3) ValueError Traceback (most recent call last) <ipython-input-6-49e4918571f1> in <module>() ----> 1 S.index('ove', 1, 3) ValueError: substring not found >>>S.rindex('o') 9 >>>S.rindex('o', 1, 5) 1 >>>S.rindex('w') ValueError Traceback (most recent call last) <ipython-input-10-5ae1ad745cf3> in <module>() ----> 1 S.rindex('w') ValueError: substring not found