Python 字串 find() 方法



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

有兩個可選引數,分別是起始索引和結束索引,它們指定了查詢子字串的範圍。如果這兩個引數未指定,則 find() 函式從第 0 個索引到字串末尾進行工作。如果在輸入字串中找不到子字串,則返回“-1”作為輸出。

在下一節中,我們將學習更多關於此方法的知識。

語法

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

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

引數

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

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

  • beg − 此引數指定起始索引。預設值為“0”。

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

返回值

如果找到則返回索引,否則返回 -1。

示例

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

str1 = "Hello! Welcome to Tutorialspoint."
str2 = "to";
result= str1.find(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.find(str2)
print("The index where the substring is found:", result)

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

The index where the substring is found: 6

示例

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

str1 = "Hello! Welcome to Tutorialspoint."
str2 = " ";
result= str1.find(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.find(str2, 5)
print("The index where the substring is found:", result)
result= str1.find(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

示例

如果在給定範圍內找不到子字串,則列印“-1”作為輸出。以下是一個例子。

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

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

The index where the substring is found: -1
python_strings.htm
廣告