Python 字串 index() 方法



Python 字串index() 方法用於返回在輸入字串中找到子字串的索引。基本上,它可以幫助我們找出指定的子字串是否出現在輸入字串中。此方法將要查詢的子字串作為必填引數。

還有兩個可選引數,即起始索引和結束索引,它們指定了查詢子字串的範圍。如果這兩個引數未指定,則index() 函式從第 0 個索引到字串末尾工作。如果在輸入字串中找不到子字串,則會引發 ValueError,這與 find() 函式不同。

在下一節中,我們將進一步學習此方法。

語法

以下是 Python 字串index() 方法的語法。

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

引數

以下是 Python 字串index() 方法的引數。

  • str - 此引數指定要搜尋的字串。

  • beg - 此引數指定起始索引。預設值為 '0'。

  • end - 此引數指定結束索引。預設值為字串的長度。

返回值

如果 Python 字串index() 函式找到子字串,則返回索引,否則引發 ValueError。

示例

以下是 Python 字串 find() 方法的示例。在這裡,我們建立了一個字串“Hello! Welcome to Tutorialspoint”,並嘗試在其中查詢單詞“to”。

str1 = "Hello! Welcome to Tutorialspoint."
str2 = "to";
result= str1.index(str2)
print("The index where the substring is found:", result)

執行上述程式後,將生成以下輸出 -

The index where the substring is found: 15

示例

空格也被視為子字串。如果輸入字串中有多個空格,則輸入字串中遇到的第一個空格將被視為結果索引。

str1 = "Hello! Welcome to Tutorialspoint."
str2 = " ";
result= str1.index(str2)
print("The index where the substring is found:", result)

執行上述程式後獲得的輸出如下 -

The index where the substring is found: 6

示例

Python 字串index() 方法返回在指定起始和結束索引範圍內找到子字串的索引。

str1 = "Hello! Welcome to Tutorialspoint."
str2 = " ";
result= str1.index(str2, 12, 15)
print("The index where the substring is found:", result)

執行上述程式後獲得的輸出如下 -

The index where the substring is found: 14

示例

如果相同的子字串在輸入字串中出現多次,則根據作為函式引數指定的起始或結束索引,獲得結果索引。

str1 = "Hello! Welcome to Tutorialspoint."
str2 = "to";
result= str1.index(str2, 5)
print("The index where the substring is found:", result)
result= str1.index(str2, 18)
print("The index where the substring is found:", result)

執行上述程式後,將顯示以下輸出 -

The index where the substring is found: 15
The index where the substring is found: 20

示例

如果在給定範圍內找不到子字串,則會引發 ValueError。

str1 = "Hello! Welcome to Tutorialspoint."
str2 = "to";
result= str1.index(str2, 25)
print("The index where the substring is found:", result)

上述程式的輸出顯示如下 -

Traceback (most recent call last):
  File "main.py", line 3, in 
    result= str1.index(str2, 25)
ValueError: substring not found
python_strings.htm
廣告