Python count()

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 

你可能感兴趣的