Thread: Nth occurence of a letter in a string

1. Nth occurence of a letter in a string

Hello,

How do we find the index of the nth occurrence of a letter in a string. For example in the following string:
>B.765.A87_43.Left.9878.xx8

how do I find the index of the 4th dot. I know how to do the leftmost and rightmost by lfind and rfind, but not the middle ones.

2. Here woud be one way to do this:
python Code:
def find_nth_character(str1, substr, n):
"""find the index of the nth substr in string str1"""
k = 0
for index, c in enumerate(str1):
#print index, c, n  # test
if c == substr:
k += 1
if k == n:
return index

str1 = "B.765.A87_43.Left.9878.xx8"
substr = '.'
occurance = 4

print "%s #%d at index %d" % (substr, occurance, find_nth_character(str1, substr, occurance))
3. No Profile Picture
Contributing User
Devshed Intermediate (1500 - 1999 posts)

Join Date
Feb 2004
Location
London, England
Posts
1,585
Rep Power
1377
The find method takes an option parameter with the position in the string to start search from. So Dietrich's function could be re-written as:

python Code:
def find_nth_character(str1, substr, n):
pos = -1
for x in xrange(n):
pos = str1.find(substr, pos+1)
if pos == -1:
return None
return pos

• Dietrich agrees : This one is fast!
4. Another way to do this is to use split and join:
Code:
#!/usr/bin/env python

def find_nth_pos(haystack, needle, n):
"Note: This returns a 0 based index"
array = haystack.split(needle)
if (len(array)-1)< n:
return -1
s = '.'.join(array[0:n])
return len(s)

str = "B.765.A87_43.Left.9878.xx8"
x = find_nth_pos(str, '.', 4)
print x
Last edited by Scorpions4ever; May 31st, 2006 at 05:35 PM.