1. 程式人生 > >床頭筆記之Python程式設計實用函式(一)

床頭筆記之Python程式設計實用函式(一)

Python count() 方法: 統計次數

用於字串str

count() 方法用於統計字串裡某個字元出現的次數。可選引數為在字串搜尋的開始與結束位置。 str.count(sub, start= 0,end=len(string))

引數

sub – 搜尋的子字串 start – 字串開始搜尋的位置。預設為第一個字元,第一個字元索引值為0。 end – 字串中結束搜尋的位置。字元中第一個字元的索引為 0。預設為字串的最後一個位置。

使用例項
	str = "this is string example....wow!!!";
	sub = "i";
	print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
	sub = "wow";
	print "str.count(sub) : ", str.count(sub)

用於列表list

count() 方法用於統計某個元素在列表中出現的次數。

list.count(obj)
使用例項
aList = [123, 'xyz', 'zara', 'abc', 123];
print "Count for 123 : ", aList.count(123);
print "Count for zara : ", aList.count('zara');