2nd iteration of a character

Anthony McDonald tonym1972/at/club-internet/in/fr
Tue Sep 23 06:38:36 EDT 2003


"Philippe Rousselot" <mailing at rousselot.rg> wrote in message
news:bkigte$1e3b$1 at biggoron.nerim.net...
> 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 ?

Most of the answers you've been given take the form (haystack, needle,
iteration), so I thought it'd be nice to write a little iterator.

class Ifind:
    def __init__(self, haystack, needle):
        self.haystack = haystack
        self.needle = needle
        self.pos = 0
    def __iter__(self):
        return self
    def next(self):
        found = self.haystack[self.pos:].find(self.needle)
        if found == -1:
            raise StopIteration
        found = self.pos + found
        self.pos = found + 1
        return found

>>> for a in Ifind("123456789012345678901234567890", "3"):
...  print a
...
2
12
22
>>>
>>> for a in Ifind("123456789012345678901234567890", "1234567890"):
...  print a
...
0
10
20
>>>
>>> for a in Ifind("123456789012345678901234567890", "nope"):
...  print a
...
>>>

Anthony McDonald






More information about the Python-list mailing list