在 Python 中,`count()` 方法是字符串對象的一個內置方法,用于統計指定子字符串在原始字符串中出現的次數。
`count()` 方法的語法如下:
string.count(substring, start=0, end=len(string))
其中,`string` 是要進行統計的原始字符串,`substring` 是要計數的子字符串,`start` 和 `end` 是可選參數,用于指定搜索的起始位置和結束位置,默認搜索整個字符串。
以下是一個使用 `count()` 方法統計字符串出現次數的示例:
my_string = "Hello, hello, hello!"
count = my_string.count("hello")
print(count)
# 輸出: 3
在上述示例中,我們調用了 `count()` 方法來統計子字符串 "hello" 在原始字符串中出現的次數,并將結果打印出來。注意,`count()` 方法是區分大小寫的,所以大寫和小寫的字符串被視為不同的子字符串。
你也可以使用可選的 `start` 和 `end` 參數來指定搜索的起始位置和結束位置,例如:
my_string = "Hello, hello, hello!"
count = my_string.count("hello", 7)
print(count)
# 輸出: 2
在上述示例中,我們從位置 7 開始搜索子字符串 "hello",并統計其出現的次數。