Skip to content

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

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

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