Using Indexes, Range and length

Hi, I’m currently working through free python programs and one of the problems is to find how many times ‘bob’ occurs in a string s.

Sample Code:
for i in range (len(s)):
if s[i:i+3]== ‘bob’
count+=1
print('Number of times bob occurs is: ’ + str(count))

What I don’t understand is why the combination of range and length have to be used in order to use s[i:i+3]. In for loops, if you were to put:
for i in s:
if s[i:i+3]== ‘bob’
count+=1
print('Number of times bob occurs is: ’ + str(count))

Why wouldn’t it work? I can see that in the IDE when the computer processes for i in s, each letter is processed. I have a quasi-sense of understanding towards this topic - but I don’t understand it to the fullest extent. Thanks so much! :slight_smile:

1 Like

using for i in s means i will be values (letters in this case), from the string, not index values

3 Likes