[Tutor] AttributeError

Hancko Kruger hanckokruger at gmail.com
Sat Feb 8 10:35:24 EST 2020


Dear sir/madam
I have been working on a program in which to solve the following problem: I need to write a program which can count how many times a certain word (“bob”) occurs within any string. The starting letter of the following ‘bob’ must also be able to be the last ‘b’ of the first ‘bob’. E.g: if I am given a string: ‘bobob’, the number of times ‘bob’ occurs within the string is: 2 times.

Currently I am using a for loop with the range being the length of the given string (s).

I have the following code:


# enter a string for 's'
s = 'aabobobaa'
countBob = 0
# the starting position for the computer to search for 'b'
start = 0
# find the position of the first 'b' within the string.
# LOOP START
for s in range(start,len(s)):
    if s[s.find('b'):(s.find('b') + 3)] == 'bob':
        countBob = countBob + 1
        start = start + s.find('b')
print('Number of times bob occurs is: ' + str(countBob))
#LOOP END


If I run the code the console keeps on giving me  an AttributeError. I have even tried the index function instead of find yet I have no luck. I do not understand what I am doing wrong. Please help.

Kind regards
Hancko


More information about the Tutor mailing list