Skip to content

Instantly share code, notes, and snippets.

@gboeer
Created December 1, 2023 10:51
Show Gist options
  • Save gboeer/b3efdd765c8edf8568d76ee4f086b8cd to your computer and use it in GitHub Desktop.
Save gboeer/b3efdd765c8edf8568d76ee4f086b8cd to your computer and use it in GitHub Desktop.
Python: Using regular expressions, return a list of all starting indices for a given substring in a string
import re
def substring_idx(text, substring):
"""Return the starting indices of all occurrences of substring in text."""
pattern = re.escape(substring)
return [match.start() for match in re.finditer(pattern, text)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment