Search code examples
pythonstringfindsubstringposition

Python program to find the 3rd position of occurrence of a given string in another given string


how to find Python program to find the 3rd position of occurrence of a given string in another given string.

find_string("I am the the champion of the champions of the champions", "the")

Solution

  • You can use a regular expression like this to find your 'needle' in a 'haystack'

    import re
    haystack = "I am the the champion of the champions of the champions"
    needle = "the"
    
    
        # print all matches
    for i, match in enumerate(re.finditer(needle, haystack)):
        print(f"{i+1}, start:{match.start()}, end:{match.end()}")
    
    # or select the third from a list
    matches = list(re.finditer(needle, haystack))  # list of all matches
    matches[2].start()  # get start position of third match
    matches[2].end()  # get end position of third match
    

    EDIT: Using only str.find

    def find_nth(haystack, needle, n):
        start, lneedle = haystack.find(needle), len(needle)
        for _ in range(n-1):
            start = haystack.find(needle, start + lneedle)
        return start
    
    find_nth(haystack, needle, 3)