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

Manprit Singh manpritsinghece at gmail.com
Fri Oct 30 20:44:52 EDT 2020


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

Regards
Manprit Singh

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

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