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

Manprit Singh manpritsinghece at gmail.com
Fri Oct 30 19:35:45 EDT 2020


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 .

Regards
Manprit Singh

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

> On 30/10/2020 15:23, Manprit Singh wrote:
>
> > st1 = "I am a boy, i am an engineer, i am a genius"
> >
> > i have to find the index of every occurrence word "am" in the string
> st1. i
> > have written a program below:
>
>
> > need to know, if this problem can be done in a more clean way ? Kindly
> give
> > some hints so that i can rewrite it in a more clean and clear way .
>
> You want to keep searching until thee are no more occurences.
> Sounds like a while loop rater than a for...
>
> >>> st1 = "I am a boy, i am an engineer, i am a genius"
> >>> help(st1.find)
> Help on built-in function find:
>
> find(...) method of builtins.str instance
>     S.find(sub[, start[, end]]) -> int
>
>     Return the lowest index in S where substring sub is found,
>     such that sub is contained within S[start:end].  Optional
>     arguments start and end are interpreted as in slice notation.
>
>     Return -1 on failure.
>
> >>> n = 0
> >>> while n != -1:
>         n = st1.find('am', n+1)
>         if n != -1: print(n)
>
>
> 2
> 14
> 32
> >>>
>
>
> --
> 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