2nd iteration of a character

Jeff Epler jepler at unpythonic.net
Sat Sep 20 17:56:57 EDT 2003


You probably want to write this in terms of find with a start argument
specified.  This minimally-tested function seems to do the job.

def findn(haystack, needle, n, start=0):
    while 1:
	idx = haystack.find(needle, start)
	if idx == -1 or n==1: break
	n -= 1
	start = idx+1
    return idx

>>> findn("axbxcx", "x", 2)
3
>>> findn("axbxcx", "z", 2)
-1

Jeff





More information about the Python-list mailing list