You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python查找字符串中相邻重叠子串'bob'的出现次数

Fixing the 'bob' Count Issue in Python

Hey there! Let's break down why your code is returning 2 instead of the correct 3 when counting the substring 'bob' in s = 'xasdkbobobasdvobob'.

The Root Problem

Chances are your original code was using a method that skips over overlapping occurrences of 'bob'. For example, if you used str.find() and jumped 3 characters ahead after each match, you'd miss the overlapping 'bob' in the bobob segment of your string. Let's look at that segment:

bobob contains two instances of 'bob' — starting at index 5 and index 7 (0-based). If you skip 3 characters after finding the first one, you'll jump past the second overlapping match entirely.

Solution 1: Iterate Through Possible Start Indices

This straightforward approach checks every possible starting position for the 3-character substring 'bob', including overlapping ones:

s = 'xasdkbobobasdvobob'
bob_count = 0

# We only need to check up to len(s)-3 (since we need 3 characters for 'bob')
for i in range(len(s) - 2):
    if s[i:i+3] == 'bob':
        bob_count += 1

print(bob_count)  # Output: 3

Solution 2: Use Regular Expressions for Overlapping Matches

If you prefer a more concise method, you can use Python's re module with a positive lookahead, which doesn't consume characters and allows overlapping matches:

import re

s = 'xasdkbobobasdvobob'
# (?=bob) matches positions where 'bob' follows, without consuming the string
bob_count = len(re.findall(r'(?=bob)', s))

print(bob_count)  # Output: 3

Both methods will correctly count all 3 occurrences of 'bob' in your string, including the overlapping one in the middle.

内容的提问来源于stack exchange,提问作者Mohamed AlNuaimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:27:07