[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 21:08:07 EDT 2020


On 31/10/2020 00:44, Manprit Singh wrote:
> Dear sir ,
> 
> Can't we write it in this way :
> st1 = "I am a boy, i am an engineer, i am a genius"
> n = 0
> while True:
>     n = st1.find('am', n)
>     if n != -1:
>         print(n)
>     elif n == -1:
>         break
>     n = n + 1

Sure you can that's just inverting the logic.
And since it saves a variable its probably preferable.

In fact, you don't need the elif, a simple else will suffice.
And of course the last line would more idiomatically be

n += 1

But it still doesn't address Mark's point about not
identifying 'am' as a separate word... Which was
explicitly stated as a requirement in your original
post:

"...to find the index of every occurrence *word* "am" ..."

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