Categories
Python Answers

How to find all occurrences of a substring with Python?

Spread the love

Sometimes, we want to find all occurrences of a substring with Python.

In this article, we’ll look at how to find all occurrences of a substring with Python.

How to find all occurrences of a substring with Python?

To find all occurrences of a substring with Python, we can use the re.finditer method.

For instance, we write:

import re

indexes = [m.start() for m in re.finditer('test', 'test test test test')]
print(indexes)

We call re.finditer method with the substring to search for and the string we’re searching for the substring in respectively.

Then we call m.start on each entry found to get the index of the start of each match.

Therefore, indexes is [0, 5, 10, 15].

Conclusion

To find all occurrences of a substring 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 *