Skip to content

Python find all occurrences in the string | Example code

  • by

Simply use the powerful regular expressions with list comprehension + start() + finditer() method to find all occurrences in the string in Python.

Example find all occurrences in a string

Simple example code

import re

s = 'Test Python Test Code Test'

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

print(res)

Output:

Python find all occurrences in the string

If you want to find overlapping matches, lookahead will do that:

import re

s = 'AA Python Code AAA'

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

print(res)

Output: [0, 1, 15, 16, 17]

Using While loop

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub)  # use start += 1 to find overlapping matches


res = list(find_all('Code Test Code Code', 'Code'))
print(res)

Output: [0, 10, 15]

Example find the number of occurrences in the list in Python

student_grades = [9.1, 8.8, 10.0, 7.7, 6.8, 8.0, 10.0, 8.1, 10.0, 9.9]

res = student_grades.count(10.0)

print(res)

Output: 3

Do comment if you have any doubts or 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 *