473,394 Members | 1,718 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

2nd iteration of a character

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 ?
Jul 18 '05 #1
5 1586
You probably want to write this in terms of find with a start argument
specified. This minimally-tested function seems to do the job.

def findn(haystack, needle, n, start=0):
while 1:
idx = haystack.find(needle, start)
if idx == -1 or n==1: break
n -= 1
start = idx+1
return idx
findn("axbxcx", "x", 2) 3 findn("axbxcx", "z", 2)

-1

Jeff

Jul 18 '05 #2
On Sat, 20 Sep 2003 23:27:23 +0200, Philippe Rousselot <ma*****@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
Jul 18 '05 #3
> 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 ?


You've already got some good answers, so how about (-:

def nth(s,ss,n): return n<len(s.split(ss)) and len(ss.join(s.split(ss)[:n]))
.... s = 'this is a test this is a test'
nth(s,'t',7) False nth(s,'t',5) 25 nth(s,'i',2) 5 nth(s,'x',2) False


Emile van Sebille
em***@fenx.com


Jul 18 '05 #4
"Philippe Rousselot" <ma*****@rousselot.rg> wrote in message
news:bk***********@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
Jul 18 '05 #5
On Tue, 23 Sep 2003 12:38:36 +0200, "Anthony McDonald" <tonym1972/at/club-internet/in/fr> wrote:
"Philippe Rousselot" <ma*****@rousselot.rg> wrote in message
news:bk***********@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
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ...
59
by: Raymond Hettinger | last post by:
Please comment on the new PEP for reverse iteration methods. Basically, the idea looks like this: for i in xrange(10).iter_backwards(): # 9,8,7,6,5,4,3,2,1,0 <do something with i> The...
2
by: Abdullah Khaidar | last post by:
Is there any iteration style we must use to get faster processing time? I've tried with some style to concat number in list. But I still don't know which one is the recommended style. >>> def...
1
by: karthigan | last post by:
I am writing a simple hardware test program in C that would run from Windows command line. Inside one of the loops, I have this code fragment that would display the Iteration count. { .......
75
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their...
0
by: mkyrou | last post by:
Community > Programming Help > .NET crystal report and iteration mkyrou Junior Member 3 Posts Today 01:09 PM #1 crystal report and iteration
9
by: news.microsoft.com | last post by:
I am looping through an iteration and I would like to test the next item but if its not the one that I want how do I put it back so that when my foreach continues it is in the next iteration? ...
4
by: John A Grandy | last post by:
Is there a performance difference between forward iteration and reverse iteration through a List<string? for ( i = 0; i < myList.Count; i++ ) { // do work, such as forward iterate through a...
1
by: greyseal96 | last post by:
Hi, I am a pretty new programmer, so I apologize in andvance if this is a dumb question... In a book that I'm reading to learn C#, it says that when using a foreach() loop, a read-only copy of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.