Find all occurrences of a substring in a string Python | Example code

Python has a built-in string function that Finds all occurrences of a substring in a string, but you could use the more powerful regular expressions.

Here is an example find all occurrences of a substring in a string using start() and re.finditer method.

You have to import the re module for this example.

import re

s = 'Code Test Python Code '

res = [m.start() for m in re.finditer('Code', s)]

print(res)

Output:

Find all occurrences of a substring in a string Python

Read more examples: Python find all occurrences in the string

Do comment if you have any doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.