python 中的count()
函數有助于返回給定字符串中給定子字符串的出現次數。方法允許在字符串中指定搜索的開始和結束。
**string.count(substring, start=..., end=...)** #Where start(index) is starts from 0
計數()參數:
count()
函數接受三個參數,其中兩個是可選的。
參數 | 描述 | 必需/可選 |
---|---|---|
子鏈 | 要查找其計數的字符串 | 需要 |
開始 | 搜索開始的字符串中的起始索引 | 可選擇的 |
目標 | 搜索結束時字符串中的結束索引 | 可選擇的 |
計數()返回值
返回值應該是一個整數,顯示子字符串在給定字符串中出現的次數。
| 投入 | 返回值 | | 線 | 整數(計數) |
Python 中count()
方法的示例
示例 1:如何計算給定子串的出現次數?
# define string
string = "I love oranges, orange are my favorite fruit"
substring = "orange"
count = string.count(substring)
# print count
print("The count of orange is:", count)
輸出:
The count of orange is: 2
示例 2:如何使用開始和結束統計給定子串的出現次數?
# define string
string = "I love oranges, orange are my favorite fruit"
substring = "orange"
count = string.count(substring,6,15)
# print count
print("The count of orange is:", count)
輸出:
The count of orange is:1