find nth occurance in a string?

Alex Martelli aleax at aleax.it
Tue Jan 15 17:36:02 EST 2002


Kevin Altis wrote:
        ...
>>>> def nthOccur(n, searchString, theString):
> ...   "finds nth occurence of searchString in theString, or
> len(theString) if < n occurrences"
> ...   return len(searchString.join(theString.split(searchString,
> n)[:n]))

A small (IMHO) enhancement:

        pieces = theString.split(searchString, n)
        if len(pieces) != n+1: return -1
        return len(TheString)-len(pieces[n])+len(searchString)

this saves the join operation, relying on the fact that the
offset must equal that simple expression on lengths (and
preserves your idea of returning -1 if no n-th occurrence
is found).

> Could some language experts please explain the relative merits of the
> various approaches? Would this make a good addition to the string methods?

I don't know if this is a frequent enough need with n large enough
and theString big enough to make performance a problem.  I doubt
it is, but that's just intuition - I have no data to base this on.


Alex




More information about the Python-list mailing list