描述
Python count() 方法用於統計字符串里某個字符出現的次數。可選參數為在字符串搜索的開始與結束位置。
語法
count()方法語法:
1 str.count(sub, start= 0,end=len(string))
參數
- sub -- 搜索的子字符串
- start -- 字符串開始搜索的位置。默認為第一個字符,第一個字符索引值為0。
- end -- 字符串中結束搜索的位置。字符中第一個字符的索引為 0。默認為字符串的最后一個位置。
返回值
該方法返回子字符串在字符串中出現的次數。
實例
以下實例展示了count()方法的實例:
1 #!/usr/bin/python 2 3 str = "this is string example....wow!!!"; 4 5 sub = "i"; 6 print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40) 7 sub = "wow"; 8 print "str.count(sub) : ", str.count(sub)
以上實例輸出結果如下:
1 str.count(sub, 4, 40) : 2 2 str.count(sub, 4, 40) : 1
list.count()描述
count() 方法用於統計某個元素在列表中出現的次數。
語法
count()方法語法:
1 list.count(obj)
參數
- obj -- 列表中統計的對象。
返回值
返回元素在列表中出現的次數。
實例
以下實例展示了 count()函數的使用方法:
1 #!/usr/bin/python 2 3 aList = [123, 'xyz', 'zara', 'abc', 123]; 4 5 print "Count for 123 : ", aList.count(123); 6 print "Count for zara : ", aList.count('zara');
以上實例輸出結果如下:
1 Count for 123 : 2 2 Count for zara : 1 3