如何用Python查找字符串中相邻重叠子串'bob'的出现次数
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:
bobobcontains 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

