Python - Extract Indices of substring matches

Python - Extract Indices of substring matches

The goal here is to extract the starting indices of all occurrences of a substring in a given string. Let's break this down step by step:

Task:

Given a string main_string and a substring sub_string, extract the starting indices of all occurrences of sub_string in main_string.

Approach:

  1. Use a loop to traverse the main_string.
  2. At each iteration, use the startswith() method or slicing to check if the substring exists from that position.
  3. If a match is found, append the current position to the result list.

Code:

def find_substring_indices(main_string, sub_string): """ Return indices of all occurrences of sub_string in main_string. """ # Create an empty list to store the indices result_indices = [] sub_length = len(sub_string) # Loop through the main string for i in range(len(main_string) - sub_length + 1): # Check if substring exists from the current position if main_string[i:i+sub_length] == sub_string: result_indices.append(i) return result_indices # Example main_string = "ababcababcaba" sub_string = "aba" print(find_substring_indices(main_string, sub_string)) # Output: [0, 5, 8, 10] 

In the example, the substring "aba" is found at indices 0, 5, 8, and 10 in the main_string.

Note: This method is simple and works efficiently for short strings. However, for larger strings or when performing multiple substring searches, more efficient algorithms like the Knuth-Morris-Pratt (KMP) or Boyer-Moore can be employed.


More Tags

blazor-server-side java python-3.3 apache2 postgresql intersection android-screen-support bdd skew rgb

More Programming Guides

Other Guides

More Programming Examples