萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python count() 方法詳解:統計子字串出現次數

方法簽名

str.count(sub, start=0, end=None) -> int

回傳 sub 在 s[start:end] 中 不重疊 出現的次數。

基本範例

>> 'abracadabra'.count('a')
5
>>> 'abracadabra'.count('abra')
2
>>> 'aaaa'.count('aa')
2        # 不重疊:位置 0-1, 2-3
>>> 'abababa'.count('aba')
2        # 位置 0, 4 (索引 2 的 aba 與前重疊被跳過)
>>> 'hello'.count('l', 1, 4)  # s[1:4] = 'ell'
2
>>> 'hello'.count('')
6        # 空字串在每個字元間 + 首尾 = len+1

關鍵特性:非重疊計數

>> 'aaa'.count('aa')
1        # 索引 0 匹配,索引 1 被跳過
# 若需重疊計數,用正則 lookahead
import re
len(re.findall(r'(?=aa)', 'aaa'))  # 2

實際應用

1. 簡易詞頻統計

2. 驗證特定字元出現次數 (如密碼策略)

def validate_password(pwd):
    return (len(pwd) >= 8 and
            pwd.count('@') >= 1 and
            sum(c.isdigit() for c in pwd) >= 2 and
            sum(c.isupper() for c in pwd) >= 1)

3. 解析固定格式:計算分隔符數量推斷欄位數

csv_line = 'a,b,c,d,e'
field_count = csv_line.count(',') + 1
print(field_count)  # 5

4. 尋找第 N 次出現位置 (配合 find/rfind)

def find_nth(s, sub, n):
    '''回傳第 n 次出現的索引 (1-based),找不到回傳 -1'''
    start = 0
    for _ in range(n):
        idx = s.find(sub, start)
        if idx == -1:
            return -1
        start = idx + 1
    return idx

print(find_nth('abracadabra', 'a', 3))  # 5 (第 3 個 a)

效能與替代方案

場景推薦
單一子字串計數str.count (C 層最快)
多子字串同時計數collections.Counter + 分詞
重疊計數re.findall(r'(?=pattern)', s)
大檔案串流計數分塊讀取 + count 累加

注意事項

  • sub 為空字串時回傳 len(s) + 1 (Python 定義)。
  • start, end 支援負索引。
  • 區分大小寫;不分大小寫計數請先 s.lower().count(sub.lower())。
copyright © 萬盛學電腦網 all rights reserved