0

I'm trying to find the count of bob in ls. I'm getting an "index out of range" error at line 10. And I can't figure it out. i should be 3.

s = 'azcbobobegghakl'
ls =[]
for x in s:
    ls.append(x)
    print(ls)

for z in ls:
    count = 0
    i = ls.index("b")
    if z[i] == "b":
        if z[i+1] == "o":
            if z[i+2] == "b":
                count +=1
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • 1
    There's a lot to comment on here, but the biggest problem is probably that `z` is a character inside `ls`, yet you are trying to index it as if it were a string/list. – pault Sep 21 '18 at 16:54
  • Possible duplicate of [string count with overlapping occurrences](https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences) – Georgy Dec 12 '18 at 15:07

3 Answers3

0

Trying to stick to the method you were trying to do by checking indexes ahead, you could do something like this :

s = 'azcbobobegghakl'
bob_count = 0 
for idx, item in enumerate(s[:-2]):
    if s[idx: idx+3] == 'bob':
        bob_count += 1

print(bob_count)
(xenial)vash@localhost:~/python/stack_overflow/sept$ python3.7 bob.py
2

You have to watch what you are indexing and what you are doing to that index as well, if you are looking ahead say index +1 and your at the final index its not going to work

vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
0

count() function of str in python.

In [31]: s ='azcbobobegghbobfdfdbob'

In [32]: print(s.count('bob'))
3

to find index of the first occurrence you can use index() function

In [34]: print(s.index('bob'))
3

to find the indexes of all the occurrences you can use re module of python

import re
In [44]: for val in re.finditer('bob', s):
    ...:     print(val.span()[0])
    ...:
3
12
19
katamit
  • 76
  • 4
0

I just explain where and why the error occured.

s = 'azcbobobegghakl'
ls =[]
for x in s:
    ls.append(x)
    print(ls)
#equal to
#ls = list(s)

for z in ls:
    count = 0
    i = ls.index("b")
    print(z) # !!!! z just a single letter,you can not use index on it !!!
    if z[i] == "b":
        if z[i+1] == "o":
            if z[i+2] == "b":
                count +=1

follow your idea,i think you want write like this:

But it is not right,because i = ls.index("b") never change,you match a same word 15 times

s = 'azcbobobegghakl'
ls =[]

for x in s:
    ls.append(x)
    print(ls)

ls = list(s)
for z in ls:
    count = 0
    i = ls.index("b")
    print(z) # z just a single letter,you can not use index on it
    if ls[i] == "b": #but ls can do this
        if ls[i+1] == "o":
            if ls[i+2] == "b":
                count +=1
print(count)

Be brief.

import re
s = 'azcbobobegghakl'
print(len(re.findall("b(?=ob)",s)))
KC.
  • 2,981
  • 2
  • 12
  • 22