[Tutor] program to find index of every occurrence of a particular word in a string

Alan Gauld alan.gauld at yahoo.co.uk
Fri Oct 30 20:05:55 EDT 2020


On 30/10/2020 23:35, Manprit Singh wrote:
> Dear Sir,
> 
> Any pacific reason for writing n+1 inside n = st1.find('am', n+1), or  you
> have just written it because the first position of "am" is not index 0, it
> is after index 0 .

There is actually a bug because my code would miss the first
'am' if it started at 0.

But the n+1 is because  find returns the index of there 'a'
If we don't increment it on the next find() call it will return
the same value each time.

>>>>> st1 = "I am a boy, i am an engineer, i am a genius"

>>>>> n = -1
      found = False
>>>>> while not found
>>         n = st1.find('am', n+1)
>>         if n == -1: found = True 
           else: print(n)

Should fix the bug.

However, Mark has raised another issue, which is that the code
is only searching for 'am' not ensuring that 'am' is a word.
For that things get more complex and I'd probably resort
to a regex... And in that case we can use findall() to
get all the occurrences in a single line.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list