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
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)
csv_line = 'a,b,c,d,e'
field_count = csv_line.count(',') + 1
print(field_count) # 5
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())。