count Tallies Non-Overlapping Hits

Count substring occurrences with str.count, which scans left to right and never counts the same bytes twice — the classic non-overlapping trap.

PythonData Integrity

Code

pythonsnippet
22 lines
blob = "aaaa"

# "aa" 命中 [0:2],扫描跳到索引 2,所以是 2 次而不是 3 次
print(blob.count("aa"))

# 空串在任何位置都匹配:len + 1
print(blob.count(""))

# 统计支持 start/end 窗口,避免切片再计数
csv_row = "a,b,c,,d"
print("empty fields:", csv_row.count(",,"))

# 真正的重叠计数需要手写步进
def overlapping(text, needle):
    hits, start = 0, text.find(needle)
    while start != -1:
        hits += 1
        start = text.find(needle, start + 1)
    return hits

print(overlapping(blob, "aa"))   # 3:[0:2] [1:3] [2:4]
print(blob.count("z"))           # 0 次也不报错

Output

Captured from a sandboxed run of this snippet in the build pipeline.

2
5
empty fields: 1
3
0

Inside the snippet

count Tallies Non-Overlapping Hits is built around the function overlapping.

Repetition is confined to while start != -1 — the rest of the file is straight-line.

What to watch for

  • The dependency list is empty; the language runtime covers it all.

Using it

The hand-stepped overlap counter is def overlapping(text, needle)

The demo output is labeled (empty fields:); each label names the call that printed it.

overlapping is the public entry point; everything else in the file exists to support it.

Key statements

def overlapping(text, needle):
    hits, start = 0, text.find(needle)
    while start != -1:
        hits += 1
        start = text.find(needle, start + 1)
    return hits

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `overlapping` at load time.