您的位置:首頁技術文章
文章詳情頁

python list的index()和find()的實現

瀏覽:2日期:2022-07-05 13:04:17

index()

Python index() 方法檢測字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結束) 范圍,則檢查是否包含在指定范圍內,該方法與 python find()方法一樣,只不過如果str不在 string中會報一個異常。

語法

index()方法語法:

str.index(str, beg=0, end=len(string))

參數

str ? 指定檢索的字符串 beg ? 開始索引,默認為0。 end ? 結束索引,默認為字符串的長度。

返回值

如果包含子字符串返回開始的索引值,否則拋出異常。

實例

>>> str1 = 'This is a example'>>> str2 = 'exam'>>>>>> str1.index(str2)10>>> str1.index(str2,5)10>>> str1.index(str2,11)Traceback (most recent call last): File '<stdin>', line 1, in <module>ValueError: substring not found>>> str1.index(str2,5,11)Traceback (most recent call last): File '<stdin>', line 1, in <module>ValueError: substring not found>>>

find()

Python find() 方法檢測字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結束) 范圍,則檢查是否包含在指定范圍內,如果包含子字符串返回開始的索引值,否則返回-1。

語法

str.find(str, beg=0, end=len(string))

參數

str ? 指定檢索的字符串 beg ? 開始索引,默認為0。 end ? 結束索引,默認為字符串的長度。

返回值

如果包含子字符串返回開始的索引值,否則返回-1。

實例

>>> str1 = 'This is a example'>>> str2 = 'exam'>>>>>> str1.find(str2)10>>> str1.find(str2,5)10>>> str1.find(str2,11)-1>>> str1.find(str2,5,11)-1>>>

到此這篇關于python list的index()和find()的實現的文章就介紹到這了,更多相關python list的index()和find()內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区