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

Manprit Singh manpritsinghece at gmail.com
Fri Oct 30 21:48:13 EDT 2020


Dear Sir,

My actual problem was  to find the index of each and every occurrence of
substring "am" in the string st1 that is solved. So now what Mark has
pointed out and you have suggested to involve regular expressions, this has
become a good exercise for me. Let me come up with an imperfect solution,
that I will share with you in the next mail .

Thanking Mark for this opportunity.

Regards
Manprit Singh


On Sat, Oct 31, 2020 at 6:38 AM Alan Gauld via Tutor <tutor at python.org>
wrote:

> 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
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list