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