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

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

技术教程推荐

从0开始学架构 -〔李运华〕

Nginx核心知识150讲 -〔陶辉〕

MySQL实战45讲 -〔林晓斌〕

玩转Spring全家桶 -〔丁雪丰〕

零基础学Java -〔臧萌〕

Go 并发编程实战课 -〔晁岳攀(鸟窝)〕

Web漏洞挖掘实战 -〔王昊天〕

Web 3.0入局攻略 -〔郭大治〕

给程序员的写作课 -〔高磊〕

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