Menu Close

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

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.

Posted in Python, Python Answers