How to find the indices of all occurrences of a substring within a string in Python

Finding all occurrences of a substring in a string results in a list containing the indices of each occurrence of the substring in the string. For example, in the string “one two three two one” the substring “two” occurs at the indices [4,14]

Solution for How to find the indices of all occurrences of a substring within a string in Python : You can use re.finditer() to to find all occurrences of a substring 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.start() for match in matches] with matches as the previous result to get a list containing only the start indices.


how-to-find-the-indices-of-all-occurrences-of-a-substring-within-a-string-in-python