描述
Python 元組 index() 方法用於從元祖中找出某個對象第一個匹配項的索引位置,如果這個對象不在元祖中會報一個異常。
語法
index() 方法語法:
T.index(obj[,start=0[,end=len(T)]])
參數
- obj -- 指定檢索的對象。
- start -- 可選參數,開始索引,默認為0。(可單獨指定)
- end -- 可選參數,結束索引,默認為元祖的長度。(不能單獨指定)
返回值
如果包含檢索的對象返回開始的索引值,否則拋出異常。
實例
以下實例展示了 index() 方法的使用方法:
# !/usr/bin/python3 T = ('Google', 'Runoob', 'Taobao') print(T.index('Taobao')) print(T.index('Google',1))
以上實例輸出結果如下:
2 Traceback (most recent call last): File "test.py", line 22, in <module> print(T.index('Google',1)) ValueError: T.index(x): x not in T