Python 字符串 count() 示例
⚡ 智能摘要
Python `string count()` 是一个内置方法,用于返回某个字符或子字符串在字符串中出现的次数。可选的 `start` 和 `end` 参数可以将搜索范围限定在文本的特定区域内。

什么是 Python 字符串计数()?
此 数() method 是一个内置函数 Python 该函数返回给定元素在字符串中出现的总次数。计数从字符串开头开始,一直到结尾。您还可以指定搜索的起始索引和结束索引。
语法为 Python 字符串计数()
此 Python string count() 函数使用以下语法:
string.count(char or substring, start, end)
参数
- 字符或子字符串: 要在给定字符串中查找的单个字符或子字符串。count() 返回该字符或子字符串在字符串中出现的次数。
- 开始: (可选)它指定搜索开始的起始索引。如果未指定,则从 0 开始。例如,当您想要搜索字符串中间的某个字符时,可以将起始值传递给 count 函数。
- 结束: (可选)它指定搜索结束的索引位置。如果未指定,则会搜索到字符串末尾。例如,如果您不想扫描整个字符串,而是希望将搜索范围限制在特定位置,则可以在计数函数中指定结束索引的值。
回报值
count() 方法会返回一个整数值,即给定字符串中指定元素的出现次数。如果给定字符串中不存在该元素,则返回 0。
示例 1:字符串上的 Count 方法
下面的例子展示了 count() 函数对字符串的运算情况。
str1 = "Hello World"
str_count1 = str1.count('o') # counting the character “o” in the givenstring
print("The count of 'o' is", str_count1)
str_count2 = str1.count('o', 0,5)
print("The count of 'o' usingstart/end is", str_count2)
输出:
The count of 'o' is 2 The count of 'o' usingstart/end is 1
示例 2:统计给定字符串中某个字符出现的次数
以下示例显示了给定字符串中某个字符的出现情况,以及使用起始索引和结束索引的情况。
str1 = "Welcome to Guru99 Tutorials!"
str_count1 = str1.count('u') # counting the character “u” in the given string
print("The count of 'u' is", str_count1)
str_count2 = str1.count('u', 6,15)
print("The count of 'u' usingstart/end is", str_count2)
输出:
The count of 'u' is 3 The count of 'u' usingstart/end is 2
示例 3:统计给定字符串中子字符串出现的次数
以下示例显示了给定字符串中子字符串的出现情况,以及使用起始索引和结束索引的情况。
str1 = "Welcome to Guru99 - Free Training Tutorials and Videos for IT Courses"
str_count1 = str1.count('to') # counting the substring “to” in the givenstring
print("The count of 'to' is", str_count1)
str_count2 = str1.count('to', 6,15)
print("The count of 'to' usingstart/end is", str_count2)
输出:
The count of 'to' is 2 The count of 'to' usingstart/end is 1
Python 列表的 count() 方法
count() 方法不限于字符串。 Python 列表和元组也提供了 `count()` 方法,用于返回特定元素在序列中出现的次数。与字符串版本不同,`list.count()` 和 `tuple.count()` 只接受要查找的元素,不接受起始索引或结束索引参数。
fruits = ['apple', 'banana', 'apple', 'grape', 'apple']
print(fruits.count('apple')) # counts how many times 'apple' appears
numbers = (1, 2, 2, 3, 2)
print(numbers.count(2)) # count() also works on a tuple
输出:
3 3
因为 count() 同时属于字符串和序列,所以无论你是计算文本中的字符数还是集合中的重复项数,同一个方法名称都适用。
如何计算重叠部分ping 发生 Python
count() 方法只统计不重叠的部分。ping 统计子字符串出现的次数。当匹配项可能重叠时,`count()` 函数返回的结果数可能比预期的要少。例如,统计“aaaa”中“aa”出现的次数,结果为 2 而不是 3,因为 `count()` 函数会跳过它找到的每一个匹配项。
text = "aaaa"
print(text.count("aa")) # non-overlapping count is 2
import re
overlaps = len(re.findall("(?=(aa))", text))
print(overlaps) # overlapping count is 3
输出:
2 3
计算重叠ping 如果匹配失败,可以使用带有前瞻断言的 re 模块,或者使用 find() 方法进行循环,每次匹配成功后将搜索位置前进一个字符。
“ 学习更多关于 Python 字符串方法
