+ 1
Is it possible to find the index of all occurrences of a substring in a a string in python?
For example, in the string “Coat goat moat”, using the substring “oa”, it should return 1 6 11
3 Respostas
+ 7
Have you heard of the high elves, I mean, regex? :>
https://code.sololearn.com/cFb42mADJjO4/?ref=app
+ 2
You can use the string method 'find'. It gives you the index of the found string.
You can tell it where to start looking.
Then write a little loop, find all the indexes and put them in a list.
Nice little practice task.
Since the RegEx solution is already given, and it's nicely short anyway, let me add the more lengthy builtin style version for reference:
occurrences = []
word = 'abracadabra'
i = 0
while True:
f = word.find('abr', i)
if f==-1:
break
occurrences.append(f)
i = f+1
print(occurrences)
0
I don’t care what form the output is in as long as it is usable