如何按特定间隔遍历字符串?求修正统计'bob'数量的Python代码
Fixing Your "bob" Counting Function
Got it, let's break down what's going wrong with your current code and get it working properly.
What's Off with the Original Code?
- You're skipping potential matches: Using
range(0, s_len+1, 3)means you only check every 3rd character as the start of "bob". But "bob" can start at any index—like in"bobob", there's a "bob" starting at index 0 and index 2, but your loop would never check index 2. - You're checking the whole string every time: The line
if bob_counter in sdoesn't look at the current position in the loop—it just checks if "bob" exists anywhere in the string. So for your example"waterbob", the loop runs 3 times (indices 0, 3, 6) and adds 1 each time, even though there's only one "bob" total. - The
else: breakis unnecessary: This stops the loop as soon as it hits a position that doesn't have "bob", which would miss any matches later in the string.
Corrected Code
Here's a fixed version that counts every single "bob" correctly, even overlapping ones:
def bobs_counter(): bob_count = 0 s = 'waterbob' bob_target = "bob" target_length = len(bob_target) string_length = len(s) # Loop through every valid starting index for "bob" for i in range(string_length - target_length + 1): # Check if the 3-character chunk starting at i is exactly "bob" if s[i:i+target_length] == bob_target: bob_count += 1 print(bob_count) bobs_counter()
What Changed (and Why)?
- Valid starting indices only:
range(string_length - target_length + 1)makes sure we only check positions where there are enough characters left to form "bob". For your 8-character string, that means indices 0 to 5 (since 5 + 3 = 8—no need to check indices 6 or 7, because you can't fit 3 characters there). - Check the exact substring: Instead of scanning the whole string each time, we grab the 3 characters starting at the current index (
s[i:i+target_length]) and compare it directly to "bob". This way, we only count matches at that specific position. - Dynamic length: Using
len(bob_target)instead of hardcoding 3 makes the function flexible—if you ever want to count a different substring later, you just changebob_target.
Test It Out
For your example "waterbob", this code will correctly print 1. If you test it with "bobbob", it'll return 2, and with "bobob" it returns 2 (catching both the "bob" at index 0 and index 2).
内容的提问来源于stack exchange,提问作者user9473137
相关产品推荐
相关产品推荐

