Method # 1: Using re
# Python code for demonstration # find the nth occurrence of a substring import re # Initializing Values ini_str = " abababababab " substr = " ab " occurrence = 4 # Find the nth occurrence of a substring inilist = [m.start () for m in re.finditer (r "ab" , ini_str)] if len (inilist)" = 4 : # Print result print ( "Nth occurrence of substring at" , inilist [occurrence - 1 ]) else : print ( "No {} occurrence of substring lies in given string" . format (occurrence)) |
Method # 2: Using the find () method
# Python code for demonstration # find the nth occurrence of the substring # Initializing values ini_str = "abababababab" sub_str = "ab" occurrence = 4 # Find the nth occurrence of a substring val = - 1 for i in range ( 0 , occurrence): val = ini_str.find (sub_str, val + 1 ) # Print n- th occurrence print ( " Nth occurrence is at " , val) |
Method # 3: Using startwith () and list comprehension
# Python code for demo # find the nth substring occurrence # Initializing values ini_str = "abababababab" substr = "ab" occurrence = 4 # Find the nth occurrence of the substring inilist = [i for i in range ( 0 , len (ini_str)) if ini_str [i:]. startswith (substr)] if len (inilist)" = 4 : # Print result print ( "Nth occurrence of substring at" , inilist [occurrence - 1 ]) else : print ( "No {} occurrence of substring lies in given string" . format (occurrence)) |
tbody>
Python | Ways to find the nth occurrence of a substring in a string find: Questions
Python | Ways to find the nth occurrence of a substring in a string Python functions: Questions