Change language

Python | Ways to find the nth occurrence of a substring in a string

| |

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))

 

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

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method