Latest web development tutorials

Python3 index()方法

Python3 字符串 Python3字符串


描述

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

語法

index()方法語法:

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

參數

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

返回值

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

實例

以下實例展示了index()方法的實例:

#!/usr/bin/python3

str1 = "w3big example....wow!!!"
str2 = "exam";

print (str1.index(str2))
print (str1.index(str2, 5))
print (str1.index(str2, 10))

以上實例輸出結果如下(未發現的會出現異常信息):

7
7
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (str1.index(str2, 10))
ValueError: substring not found

注意:在接下來的幾個章節中,我們會詳細介紹Python Exception的使用。


Python3 字符串 Python3字符串