在python中統計字符串或者列表中某個字符或者數字出現的次數(count函數)


count函數
count   漢語翻譯   計數,包括,總數,把..... 算入
這里我們可以翻譯成把.... 算入,或者包括的意思,例如例1 含義就是s 字符串中總共包含多少個word 字符串
count 的格式  count(sub,start=0,end=len(string))
參數的含義分別是sub ,要收索的字符串或者數字,start 開始的位置,默認是開始位置0 end 搜索的結束位置,默認是總長度
s= 'hello word ,my word'
#1
word_count = s.count( 'word')
print(word_count)     # 2
#2
word1 = s.count( 'o')   #3     統計整個字符串中o出現的次數
word2 = s.count( 'o',1,2) # 0 因為開始位置和結束位置不包含 o 字母,所以返回為 0
print(word1)
print(word2)
同樣的道理也可以獲取列表中的值
li = [ 'hello', 'word' , 'my', 'word',10,20,30,10]
word = li.count( 'word')
l_10 = li.count(10)
print(word)    #2
print(l_10)    #2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM