Python 字串 count() 方法



python 字串count()方法用於計算指定為函式引數的子字串在字串中不重疊出現的次數。

還可以透過在函式的引數中指定範圍的開始和結束來獲得子字串在該字串特定範圍內的計數。開始和結束是可選引數,其解釋方式與切片表示法相同。如果子字串為空,則返回字元之間空字串的數量,即字串長度加一。

在以下部分,我們將學習更多關於 python 字串count()方法的詳細資訊。

語法

python 字串count()方法的語法如下。

str.count(sub, start= 0,end=len(string))

引數

以下是 python 字串count()方法的引數。

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

  • start − 此引數是一個整數值,指定搜尋開始的起始索引。第一個字元從索引“0”開始。如果未指定 start 值,則預設值為“0”,即第一個索引。

  • end − 此引數是一個整數值,指定搜尋結束的結束索引。如果未指定此值,則預設搜尋結束於最後一個索引。

返回值

python 字串count()方法返回給定輸入字串中子字串出現的次數。

示例

python 字串count()方法以子字串、開始和結束值作為其引數,返回指定範圍內子字串出現的次數。

在下面的示例中,建立了一個字串“Hello! Welcome to Tutorialspoint.”。然後將要計數的子字串指定為“i”。之後,在字串上呼叫count()函式,並以 3 作為開始值和 30 作為結束值作為其引數。

str = "Hello! Welcome to Tutorialspoint.";
substr = "i";
print("The number of occurrences of the substring in the input string are: ", str.count(substr, 3, 30))

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

The number of occurrences of the substring in the input string are:  2

示例

如果函式引數中未指定結束值,則字串的最後一個索引被視為預設結束值。

以下是一個使用 Python 字串 **count()** 函式計算給定字串中子字串出現次數的示例。在這個程式中,建立了一個字串並指定了子字串。然後,在字串上呼叫 **count()** 函式,並將子字串和起始值作為其引數。

str = "Hello! Welcome to Tutorialspoint.";
substr = "to";
print("The number of occurrences of the substring in the input string are: ", str.count(substr, 21))

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

The number of occurrences of the substring in the input string are:  0

示例

如果函式引數中未指定起始值和結束值,則字串的第零個索引被視為預設起始值,字串的最後一個索引被視為預設結束值。

以下是一個使用 Python 字串 **count()** 函式計算給定字串中子字串出現次數的示例。

str = "Hello! Welcome to Tutorialspoint.";
substr = "t";
print("The number of occurrences of the substring in the input string are: ", str.count(substr))

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

The number of occurrences of the substring in the input string are:  3

示例

如果函式引數中未指定起始值和結束值,則字串的第零個索引被視為預設起始值,字串的最後一個索引被視為預設結束值。如果子字串為空,則返回字元之間空字串的數量,即字串長度加一。

在以下 **count()** 函式示例中,建立了一個字串並指定了一個空子字串。然後,在字串上呼叫 **count()** 函式,不提供起始值和結束值。

str = "Hello! Welcome to Tutorialspoint.";
substr = "";
print("The number of occurrences of the substring in the input string are: ", str.count(substr))

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

The number of occurrences of the substring in the input string are:  34

示例

子字串是 Python 字串 **count()** 方法的必填引數。如果未指定此引數,則會發生型別錯誤。

以下是一個使用 Python 字串 **count()** 函式計算輸入字串中子字串出現次數的示例。在以下示例中,建立了一個字串。然後,在字串上呼叫 **count()** 函式,並將起始值和結束值作為其引數,但未指定要計數的子字串。

str = "Hello! Welcome to Tutorialspoint.";
print("The number of occurrences of the substring in the input string are: ", str.count(2, 21))

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

Traceback (most recent call last):
  File "main.py", line 2, in 
    print("The number of occurrences of the substring in the input string are: ", str.count(2, 21))
TypeError: must be str, not int
python_strings.htm
廣告