string 中 某字符 的次数
语法:
str.count(sub, start= 0,end=len(string))
参数
sub -- 搜索的子字符串
start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
返回值
该方法返回子字符串在字符串中出现的次数。
实例
以下实例展示了count()方法的实例:
>>>string = 'Hello World! Hello Python! I love python!' >>>string.count('o') 6 >>>string.count('o', 5, 20) 2 >>>string.count('o',0,20) 3 >>>string.count('o', 5, 1000) # 随便取个 无限大的 end 参数 5
list 中 某元素 的次数
语法
list.count(obj)
obj是要搜索的元素。
>>>list_1 = [10, 20, 30, 'Hello', 10, 20, 10] >>>list_1.count(10) 3 >>>list_1.count(20) 2