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?
Using regular expressions, you can use
re.finditer
to find all (non-overlapping) occurences:Alternatively, if you don't want the overhead of regular expressions, you can also repeatedly use
str.find
to get the next index:This also works for lists and other sequences.
For your list example:
If you wanted all the items in a list that contained 'll', you could also do that.
Brand new to programming in general and working through an online tutorial. I was asked to do this as well, but only using the methods I had learned so far (basically strings and loops). Not sure if this adds any value here, and I know this isn't how you would do it, but I got it to work with this:
You can split to get relative positions then sum consecutive numbers in a list and add (string length * occurence order) at the same time to get the wanted string indexes.
A simple iterative code which returns a list of indices where the substring occurs.