Python index和rindex方法

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 – 可選參數,結束查找位置,默認爲字符串的長度。(不能單獨指定)

返回值

返回子字符串最後一次出現在字符串中的的索引位置,如果沒有匹配項則會報一個異常。

'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ羣:579817333 
尋找有志同道合的小夥伴,互幫互助,羣裏還有不錯的視頻學習教程和PDF電子書!
'''
>>>S = 'love python!'
>>>S.index('ove')
>>>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)
>>>S.index('ove', 1, 4)
>>>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')
>>>S.rindex('o', 1, 5)
>>>S.rindex('w')
ValueError                                Traceback (most recent call last)
<ipython-input-10-5ae1ad745cf3> in <module>()
----> 1 S.rindex('w')

ValueError: substring not found
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章