2nd iteration of a character

Bengt Richter bokr at oz.net
Sat Sep 20 18:04:53 EDT 2003


On Sat, 20 Sep 2003 23:27:23 +0200, Philippe Rousselot <mailing at rousselot.rg> wrote:

>Hi,
>
>How do I find the second iteration of a character in a string using python
>
>this gives me the first one
>f1 = string.find(line,sub)
>
>this the last one
>f2 = string.rfind(line,sub)
>
>but for the nth one ?
>
>Thanks in advance
>
>Philippe
>
>PS : any good book to recommend ?
Online tutorials first ;-)


 >>> s='01x34x678x012345x789x'
 >>> def find_nth(s, ss, n):
 ...     i = -len(ss)
 ...     for j in xrange(n):
 ...         i += len(ss)
 ...         i = s.find(ss,i)
 ...         if i<0: return i
 ...     return i<0 and -1 or i
 ...
 >>> find_nth(s,'x', 1)
 2
 >>> find_nth(s,'x', 2)
 5
 >>> find_nth(s,'x', 3)
 9
 >>> [find_nth(s,'x', i) for i in xrange(5)]
 [-1, 2, 5, 9, 16]
 >>> [find_nth(s,'x7', i) for i in xrange(5)]
 [-1, 16, -1, -1, -1]
 >>> [find_nth(s,'01', i) for i in xrange(5)]
 [-1, 0, 10, -1, -1]
 >>> [find_nth(s,'34', i) for i in xrange(5)]
 [-1, 3, 13, -1, -1]
 >>> [find_nth(s,'xx', i) for i in xrange(5)]
 [-1, -1, -1, -1, -1]

BTW, the above is not the fastest possible code, just a quick first prototype,
and not tested beyond what you see above ;-)


Regards,
Bengt Richter




More information about the Python-list mailing list