python count使用方法
Python 中的 count() 方法用于统计字符串、列表、元组中某个元素出现的次数。
语法:
str.count(sub[, start[, end]])
list.count(obj)
tuple.count(obj)
参数说明:
- str:表示原始字符串,必须。
- sub:表示要查找的子字符串,必须。
- start:表示查找的起始位置,可选。
- end:表示查找的结束位置,可选。
返回值:
返回子字符串在字符串中出现的次数。
示例:
字符串示例:
str = "hello world"
统计字符 "o" 出现的次数:
print(str.count("o")) # 2
统计字符串 "llo" 出现的次数:
print(str.count("llo")) # 1
列表示例:
list = [1, 2, 3, 2, 2, 4, 5, 6]
统计元素 2 出现的次数:
print(list.count(2)) # 3
元组示例:
tuple = (1, 2, 3, 2, 2, 4, 5, 6)
统计元素 2 出现的次数:
print(tuple.count(2)) # 3
原文地址: http://www.cveoy.top/t/topic/Kvg 著作权归作者所有。请勿转载和采集!