Python count函数详解与用法指南
Python 的 count()
函数用于计算子字符串或某个元素在字符串或序列(如列表、元组)中出现的次数。
1. 在字符串中使用 count()
语法:
str.count(sub[, start[, end]])
sub
: 要查找的子字符串。start
: (可选)查找的起始位置。end
: (可选)查找的结束位置。示例:
text = "hello world, hello Python"
# 计算 "hello" 出现的次数
print(text.count("hello")) # 输出: 2
# 指定范围
print(text.count("hello", 0, 10)) # 输出: 1
2. 在列表中使用 count()
语法:
list.count(element)
element
: 要统计的元素。示例:
nums = [1, 2, 3, 4, 2, 2, 5]
# 计算 2 出现的次数
print(nums.count(2)) # 输出: 3
# 计算字符串在列表中出现的次数
words = ["apple", "banana", "apple", "cherry"]
print(words.count("apple")) # 输出: 2
3. 在元组中使用 count()
与列表用法相同,count()
可以计算某个元素在元组中出现的次数。
示例:
numbers = (1, 2, 3, 2, 2, 4)
# 计算 2 出现的次数
print(numbers.count(2)) # 输出: 3
注意事项
-
区分大小写:
count()
在字符串中是区分大小写的。text = "Hello hello" print(text.count("hello")) # 输出: 1
-
子字符串可以重叠:
如果子字符串重叠,count()
会按非重叠的方式统计。text = "aaa" print(text.count("aa")) # 输出: 1
-
范围边界:
当使用start
和end
指定范围时,统计的范围为[start, end)
,不包括end
位置。text = "hello world" print(text.count("o", 5, 10)) # 输出: 1
作者:阳来了