Tutorial Study Image

Python count()

Python 中的 count() 函数有助于返回给定字符串中给定子字符串的出现次数。该方法允许指定在字符串中搜索的起始和结束位置。


string.count(substring, start=..., end=...) #Where start(index) is starts from 0
 

count() 参数

count() 函数接受三个参数,其中两个是可选的。

参数 描述 必需/可选
子字符串 要查找其出现次数的字符串 必需
起始 字符串中开始搜索的起始索引 可选
end 字符串中结束搜索的结束索引 可选

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