简体   繁体   中英

Index error when trying to count occurrences of a string with overlapping

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

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

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

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM