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

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

技术教程推荐

机器学习40讲 -〔王天一〕

React实战进阶45讲 -〔王沛〕

重学前端 -〔程劭非(winter)〕

Vue开发实战 -〔唐金州〕

许式伟的架构课 -〔许式伟〕

Java业务开发常见错误100例 -〔朱晔〕

Django快速开发实战 -〔吕召刚〕

Go 语言项目开发实战 -〔孔令飞〕

大厂设计进阶实战课 -〔小乔〕

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