关于含range、len与切片的Python字符串统计代码运行原理的问询
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, theni+1, theni+2(since we stop ati+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', socountincreases to 1. - When
i=6:s[6:9]pulls characters at positions 6,7,8 →'b'+'o'+'b'→ another match, socountjumps to 2. - For every other
ivalue, the 3-character slice won't match'bob', socountstays 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

