Python count() 方法: 统计次数
用于字符串string
count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
string.count(sub, start= 0,end=len(string))
参数
sub – 搜索的子字符串
start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end – 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
使用实例
test_str = "test example!";
sub = "e";
print "test_str .count(sub, 3, 10) : ", test_str .count(sub, 3, 10)
sub = "test";
print "test_str .count(sub) : ", test_str .count(sub)
用于列表list
count() 方法用于统计某个元素在列表中出现的次数。
list.count(obj)
使用实例
List_test = ['abcxd', 'ccc', 'dad', 'beibi', 456, 'beibi'];
print "Count for beibi: ", List_test .count('beibi');
print "Count for ccc: ", List_test .count('ccc');