Skip to content

Instantly share code, notes, and snippets.

@vagelim
Last active November 30, 2015 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vagelim/37e421040f278c3750d6 to your computer and use it in GitHub Desktop.
Save vagelim/37e421040f278c3750d6 to your computer and use it in GitHub Desktop.
Find the nth occurrence of a substring in a given string
def find_nth(haystack, needle, n):
"""Take a string (haystack) and find start the nth occurrence of the substring (needle)"""
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment