find the kth index of a substring in a string in python

You can use the index() method to find the index of a substring in a string. However, the index() method only returns the index of the first occurrence of the substring. To find the kth occurrence of the substring, you can use a loop with the index() method.

Here's an example function that finds the kth index of a substring in a string:

main.py
def find_kth_index(string, substring, k):
    index = -1
    for i in range(k):
        index = string.find(substring, index + 1)
        if index == -1:
            return -1
    return index
193 chars
8 lines

The find() method searches for the substring starting from the index parameter. By setting index to the previous occurrence of the substring and adding 1, we can search for the next occurrence of the substring.

Here's an example usage of the function:

main.py
string = "hello world"
substring = "l"
k = 3
kth_index = find_kth_index(string, substring, k)
print(kth_index)  # output: 9
124 chars
6 lines

In this example, the function finds the third occurrence of the character "l" in the string "hello world", which is at index 9.

gistlibby LogSnag