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

关于含range、len与切片的Python字符串统计代码运行原理的问询

Understanding the "Count Bob Occurrences" Python Code

First, let's look at the full code again for reference:

s = 'eljwboboblejr' # dont paste into grader
count = 0
for i in range (len(s)):
    if s[i:i+3]== 'bob':
        count+=1
print('Number of times bob occurs is: ' + str(count))

Let's break down the parts you're confused about one by one, using our example string to make it concrete.

What does len(s) do here?

len(s) calculates the total number of characters in the string s. For our example, 'eljwboboblejr' has 12 characters, so len(s) returns 12.

The range(len(s)) part creates a sequence of numbers from 0 to 11 (since range() stops one number short of its input). We use this sequence to loop through every possible starting index in the string.

You might notice that when i is 10 or 11, we can't get a full 3-character chunk from the string — but that's okay! Python's slicing just returns whatever characters are left (1 or 2 characters in those cases), which can't match the 3-character 'bob', so those iterations don't affect our count. The code works perfectly fine this way.

How does s[i:i+3] == 'bob' work?

This uses Python's string slicing to check if a 3-character chunk of s starting at index i exactly matches 'bob'.

Here's how slicing works: s[start:end] grabs all characters from the start index up to (but not including) the end index. So s[i:i+3] means:

  • Start at position i
  • Take the character at i, then i+1, then i+2 (since we stop at i+3)

Let's walk through our example:

  • When i=4: s[4:7] pulls characters at positions 4, 5, 6 → 'b'+'o'+'b' → this matches 'bob', so count increases to 1.
  • When i=6: s[6:9] pulls characters at positions 6,7,8 → 'b'+'o'+'b' → another match, so count jumps to 2.
  • For every other i value, the 3-character slice won't match 'bob', so count stays the same.

By the end of the loop, count holds the total number of times 'bob' appears in the string — which is 2 for our example.

内容的提问来源于stack exchange,提问作者J. Zalewski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:14:03