Explore Courses Blog Tutorials Interview Questions
+2 votes
1 view
in Python by (47.6k points)

Python has string.find() and string.rfind() to get the index of a substring in a string.

I'm wondering whether there is something like string.find_all() which can return all found indexes (not only the first from the beginning or the first from the end).

For example:

string = "test test test test"

print string.find('test') # 0

print string.rfind('test') # 15

#this is the goal

print string.find_all('test') # [0,5,10,15]

1 Answer

0 votes
by (106k points)
edited by

To find all occurrences of a substring Python does not have any built-in string function that does what you're looking for, but you could use the more powerful regular expressions:

import re

string = "test test test test"

[m.start() for m in re.finditer('test', 'test test test test')] 


To know more about this you can have a look at the following video:-

Related questions

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories