count()
方法返回子字符串在给定字符串中出现的次数。
示例
message = 'python is popular programming language'
# number of occurrence of 'p'
print('Number of occurrence of p:', message.count('p'))
# Output: Number of occurrence of p: 4
字符串 count 语法
count()
方法的语法是
string.count(substring, start=..., end=...)
count() 参数
count()
方法只需要一个参数即可执行。但是,它也有两个可选参数
- substring - 要查找出现次数的字符串。
- start (可选) - 字符串中搜索开始的起始索引。
- end (可选) - 字符串中搜索结束的结束索引。
注意: Python 中的索引从 0 开始,而不是 1。
count() 返回值
count()
方法返回子字符串在给定字符串中出现的次数。
示例 1:计算给定子字符串出现的次数
# define string
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
# print count
print("The count is:", count)
输出
The count is: 2
示例 2:使用 start 和 end 计算给定子字符串出现的次数
# define string
string = "Python is awesome, isn't it?"
substring = "i"
# count after first 'i' and before the last 'i'
count = string.count(substring, 8, 25)
# print count
print("The count is:", count)
输出
The count is: 1
在这里,计数从第一个 i
被遇到之后开始,即 第 7
个索引位置。
并且,它在最后一个 i
之前结束,即 第 25
个索引位置。
另请阅读