[Tutor] program to find index of every occurrence of a particular word in a string
Mark Lawrence
breamoreboy at gmail.com
Fri Oct 30 11:41:00 EDT 2020
On 30/10/2020 15:23, Manprit Singh wrote:
> Dear sir ,
>
> Consider a string
> 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:
>
> st1 = "I am a boy, i am an engineer, i am a genius"
> w ="am"
> for i in range(len(st1)):
> if st1.find(w, i, i + len(w)) != -1:
> print(i)
> 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 .
I suggest that you rewrite it so that it works, e.g. in a string like
"spam spam spam" it will find all of the "am"s. Then rewrite it again,
starting by getting rid of the 'range(len' which is almost always a code
smell in python.
>
> Regards
> Manprit Singh
>
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list