[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 16:17:43 EDT 2020


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




More information about the Tutor mailing list