[Tutor] AttributeError
Mats Wichmann
mats at wichmann.us
Sat Feb 8 12:36:36 EST 2020
On 2/8/20 8:35 AM, Hancko Kruger wrote:
> 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.
It really helps if you post the actual error message, because it
contains real clues. In this case I can see what's wrong without it, but
keep that in mind...
when you loop over a range object you are getting a number which you
assign to s. Then you do s.find ... I'll bet the AttributeError is that
an int has no find method.
The real problem here is you're reusing 's': it holds the string you're
trying to look up in, and then you throw that away by assigning
something different to s in the for loop.
There are better ways to solve this problem, but let's talk about that
later, when you've fixed this one up first.
More information about the Tutor
mailing list