How do I find multiple occurrences of a string within a string in Python? Consider this:
>>> text = "Allowed Hello Hollow"
>>> text.find("ll")
1
>>>
So the first occurrence of ll
is at 1 as expected. How do I find the next occurrence of it?
Same question is valid for a list. Consider:
>>> x = ['ll', 'ok', 'll']
How do I find all the ll
with their indexes?
I think what you are looking for is
string.count
Hope this helps
NOTE: this only captures non-overlapping occurences
This program counts the number of all substrings even if they are overlapped without the use of regex. But this is a naive implementation and for better results in worst case it is advised to go through either Suffix Tree, KMP and other string matching data structures and algorithms.
Maybe not so Pythonic, but somewhat more self-explanatory. It returns the position of the word looked in the original string.
This link explains how to do the whole thing in O(n) and includes a solution in python as well.
If you go further down the sets to 'Suffix trees' you'd be able to do the same thing if you had one big string but wanted to search for 1000s of patterns in it.
I think there's no need to test for length of text; just keep finding until there's nothing left to find. Like this: