find nth occurance in a string?

Kevin Altis altis at semi-retired.com
Tue Jan 15 19:45:58 EST 2002


Here's my modified version of the solution in the original thread on find
nth. I changed the variable names to protect the innocent, but otherwise it
is basically the same ;-)

# original function by Steve Purcell
def findnth(s, substr, n):
    """find the nth occurance of substr in s

    return the offset"""
    offset = -1
    for i in xrange(n):
        offset = s.find(substr, offset+1)
        if offset == -1: break
    return offset

ka

"Alex Martelli" <aleax at aleax.it> wrote in message
news:m9218.2502$WS2.76391 at news1.tin.it...
> 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