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

Question:

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")
Asked By: kreety kishore

||

Answers:

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)
Answered By: bitflip

You can do like this,

def find_string(txt, str1, n):
    index = 0
    for i in range(n + 1):
        index = txt.find(str1, index + 1)
    return txt.find(str1, index)

Output:

find_string("I am the the champion of the champions of the champions", "the", 3)
# Output
# 42
Answered By: Rahul K P