Python | Ways to find nth occurrence of substring in a string
Given a string and a substring, write a Python program to find the nth occurrence of the string. Let’s discuss a few methods to solve the given task.
Method #1: Using re
# Python code to demonstrate # to find nth occurrence of substring import re # Initialising values ini_str = "abababababab"substr = "ab"occurence = 4 # Finding nth occurrence of substring inilist = [m.start() for m in re.finditer(r"ab", ini_str)] if len(inilist)>= 4: # Printing result print ("Nth occurrence of substring at", inilist[occurence-1]) else: print ("No {} occurrence of substring lies in given string".format(occurence)) |
chevron_right
filter_none
Method #2: Using find() method
# Python code to demonstrate # to find nth occurrence of substring # Initialising values ini_str = "abababababab"sub_str = "ab"occurence = 4 # Finding nth occurrence of substring val = -1for i in range(0, occurence): val = ini_str.find(sub_str, val + 1) # Printing nth occurrence print ("Nth occurrence is at", val) |
chevron_right
filter_none
Method #3: Using startswith() and list comprehension
# Python code to demonstrate # to find nth occurrence of substring # Initialising values ini_str = "abababababab"substr = "ab"occurence = 4 # Finding nth occurrence of substring inilist = [i for i in range(0, len(ini_str)) if ini_str[i:].startswith(substr)] if len(inilist)>= 4: # Printing result print ("Nth occurrence of substring at", inilist[occurence-1]) else: print ("No {} occurrence of substring lies in given string".format(occurence)) |
chevron_right
filter_none
Recommended Posts:
- Python | Get the string after occurrence of given substring
- Python | Find last occurrence of substring
- Python | Ways to count number of substring in string
- Python program to find occurrence to each character in given string
- Python | Ways to find all permutation of a string
- Find length of a string in python (4 ways)
- Python | Split string on Kth Occurrence of Character
- Python | Ways to split a string in different ways
- Generate two output strings depending upon occurrence of character in input string in Python
- Python | All occurrences of substring in string
- Python | Frequency of substring in given string
- Python | Remove the given substring from end of string
- Python | Count overlapping substring in a given string
- Python | Check if a Substring is Present in a Given String
- Python | Get the substring from given string using list slicing
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : nidhi_biet



