Python count函式使用方法例項解析
阿新 • • 發佈:2020-03-24
Python count()方法
描述
Python count() 方法用於統計字串裡某個字元出現的次數。可選引數為在字串搜尋的開始與結束位置。
count()方法語法:
str.count(sub,start= 0,end=len(string))
引數
- sub -- 搜尋的子字串
- start -- 字串開始搜尋的位置。預設為第一個字元,第一個字元索引值為0。
- end -- 字串中結束搜尋的位置。字元中第一個字元的索引為 0。預設為字串的最後一個位置。
返回值
該方法返回子字串在字串中出現的次數。
以下例項展示了count()方法的例項:
例項(Python 2.0+)
#!/usr/bin/python str = "this is string example....wow!!!"; sub = "i"; print "str.count(sub,4,40) : ",str.count(sub,40) sub = "wow"; print "str.count(sub) : ",str.count(sub)
以上例項輸出結果如下:
str.count(sub,40) : 2
str.count(sub) : 1
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。