+ 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

24th Jan 2020, 6:48 AM
Calculator Ramen
Calculator Ramen - avatar
3 ответов
+ 7
Have you heard of the high elves, I mean, regex? :> https://code.sololearn.com/cFb42mADJjO4/?ref=app
24th Jan 2020, 7:00 AM
Fermi
Fermi - avatar
+ 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)
24th Jan 2020, 9:26 AM
HonFu
HonFu - avatar
0
I don’t care what form the output is in as long as it is usable
24th Jan 2020, 6:49 AM
Calculator Ramen
Calculator Ramen - avatar