Categories
Python Answers

How to find the nth occurrence of substring in a string with Python?

Spread the love

Sometimes, we want to find the nth occurrence of substring in a string with Python.

In this article, we’ll look at how to find the nth occurrence of substring in a string with Python.

How to find the nth occurrence of substring in a string with Python?

To find the nth occurrence of substring in a string with Python, we can use the re.finditer method.

For instance, we write

import re

s = "ababdfegtduab"
indexes = [m.start() for m in re.finditer(r"ab", s)]

to create a list of indexes with the matches we’re looking for in string s by calling re.finditer with the regex pattern we’re looking for and s.

Then we call m.start to get the index of a instance of the match in the loop.

Conclusion

To find the nth occurrence of substring in a string with Python, we can use the re.finditer method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *