Python 字符串 count()

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 个索引位置。


另请阅读

在我们结束之前,让我们测试一下你对 Python 字符串 count() 的知识!你能解决下面的挑战吗?

挑战

编写一个函数来查找字符串中字符的出现次数。

  • 例如,输入 'hello world''o',输出应该是 2
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战