Python3 中的 count(string,begin,end)

首页 / Python3入门教程 / Python3 中的 count(string,begin,end)

它返回指定范围内子字符串的出现次数。它包含三个参数,第一个是子字符串,第二个是起始索引,第三个是范围的最后一个索引。开始和结束都是可选的,而子字符串是必需的。

count - 语法

count(sub[, start[, end]])

count - 参数

  • sub (必需)
  • start(可选)
  • end(可选)

count - 返回

它返回该范围内子字符串出现的次数。

让无涯教程看一些示例来了解count()方法。

# Python count() function example
# 变量声明
str = "Hello Learnfk"
str2 = str.count('t')
# 显示结果
print("occurences:", str2)

输出

occurences: 2
count - Python String Count()方法示例2
# Python count() function example
# 变量声明
str = "ab bc ca de ed ad da ab bc ca"
oc = str.count('a')
# 显示结果
print("occurences:", oc)

在这里,无涯教程传递第二个参数(起始索引)。

无涯教程网

# Python count() function example
# 变量声明
str = "ab bc ca de ed ad da ab bc ca"
oc = str.count('a', 3)
# 显示结果
print("occurences:", oc)

输出

occurences: 5

以下示例使用所有三个参数,并从指定范围返回结果.

# Python count() function example
# 变量声明
str = "ab bc ca de ed ad da ab bc ca"
oc = str.count('a', 3, 8)
# 显示结果
print("occurences:", oc)

输出

occurences: 1

它也可以计算非字母字符,请参见以下示例。

# Python count() function example
# 变量声明
str = "ab bc ca de ed ad da ab bc ca 12 23 35 62"
oc = str.count('2')
# 显示结果
print("occurences:", oc)

输出

occurences: 3

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Service Mesh实践指南 -〔周晶〕

微服务架构实战160讲 -〔杨波〕

从0打造音视频直播系统 -〔李超〕

高并发系统设计40问 -〔唐扬〕

分布式协议与算法实战 -〔韩健〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

Vue 3 企业级项目实战课 -〔杨文坚〕

Dubbo源码剖析与实战 -〔何辉〕

结构思考力 · 透过结构看思考 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)