2nd iteration of a character
Bengt Richter
bokr at oz.net
Sat Sep 27 00:17:23 EDT 2003
On Tue, 23 Sep 2003 12:38:36 +0200, "Anthony McDonald" <tonym1972/at/club-internet/in/fr> wrote:
>"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
Carrying on with that theme ...
You could use the re module, e.g., (observing that a constant string with no magic characters
is a simple regular expression, though you could of course make up more complex things with re).
>>> import re
>>> for mo in re.finditer("3", "123456789012345678901234567890"): print mo.start()
...
2
12
22
>>>>
>>>> for a in Ifind("123456789012345678901234567890", "1234567890"):
>... print a
>...
>0
>10
>20
>>> for mo in re.finditer("1234567890", "123456789012345678901234567890"): print mo.start()
...
0
10
20
>>>>
>>>> for a in Ifind("123456789012345678901234567890", "nope"):
>... print a
>...
>>> for mo in re.finditer("nope", "123456789012345678901234567890"): print mo.start()
...
>>>
Or if you do want to roll your own find-based iterable, the generator version seems easier to me:
>>> def ifind(haystack, needle):
... pos=0; skip = len(needle)
... while 1:
... pos = haystack.find(needle, pos)
... if pos<0: break
... yield pos
... pos += skip
...
>>> for i in ifind("123456789012345678901234567890", "3"): print i
...
2
12
22
>>> for i in ifind("123456789012345678901234567890", "1234567890"): print i
...
0
10
20
>>> for i in ifind("123456789012345678901234567890", "nope"): print i
...
>>>
Regards,
Bengt Richter
More information about the Python-list
mailing list