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