"find()" function

here we can clearly see that there are more than one “o” in the string. but it showing me the location of first “o”. how can I get locations of all the “o” present in the string?

Hi @Odibumba,
This can have various solutions like looping over all chars, using a combination of recursion and slicing, using enumerate and loop.
I would recommend you to please give it a try at your own once, come up with a simple solution and we’ll try to optimize it further.

1 Like

Hi Odibumba,

So if your requirement is to count the number of occurrences then you can chose to use count () function.

For ex :
string = “hi padhai team how are you”
str_find = “a”
count = string.count(str_find)
Print the count variable to see the output.

If you need to find the number of occurrences of a letter in a string you can possibly use the the simple ‘for’ loop.

string = “hi padhai, how are you”
str_find = “a”

temp = 0
for i in range (0, len(string)): # to interate until the string ends#
if string[i] == str_find # to match if the letter is found in the string
a =a+1
If the value of ‘a’ is 0 then there is no match found. If the ‘a’ have some value then it has that many occurrences.

4 Likes

“using a combination of recursion and slicing” - sorry, will you please explain this please.

The idea is to pass a string to a function (which uses .find() to print/store index of a char), and recursively call it for a sliced string.

``````def indexes(string, substring, skipped=0):
indx = string.find(substring)
if indx > -1:
print(indx+skipped)
indexes(string[indx+1:], substring, skipped+indx+1)
else:
return 0
``````
2 Likes