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)
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 number of occurrences in 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)
Do comment if you have any doubts and suggestions on this Python string topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.