Last active
November 30, 2015 18:56
-
-
Save vagelim/37e421040f278c3750d6 to your computer and use it in GitHub Desktop.
Find the nth occurrence of a substring in a given string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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