1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2004
    Rep Power

    Nth occurence of a letter in a string


    How do we find the index of the nth occurrence of a letter in a string. For example in the following string:

    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.

    Thanks for your help.
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Rep Power
    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))
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    London, England
    Rep Power
    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

    Comments on this post

    • Dietrich agrees : This one is fast!
  6. #4
  7. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Woodland Hills, Los Angeles County, California, USA
    Rep Power
    Another way to do this is to use split and join:
    #!/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.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo