How to find all occurrences of a substring?

619    Asked by IanRobertson in Devops , Asked on Jul 18, 2021

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]

Answered by Rachel Kerr

 To find all occurrences of a substring in a string 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')]

Or

Use re. finditer() to to find all occurrences of a substring in a string

Call re. finditer(pattern, string) with pattern as the desired substring to get an iterable object containing the start and end indices of each occurrence of pattern in string . Use a list comprehension with the syntax [match.



Your Answer

Interviews

Parent Categories