Home >Backend Development >Python Tutorial >How Can I Efficiently Count Overlapping String Occurrences in Python?
Overlapping String Occurrence Counting in Python
When it comes to counting string occurrences, overlooking overlaps can lead to incorrect results. One common approach is to loop over the string character by character, but this can be inefficient for larger strings.
Is There a Better Way?
Yes, there is a more efficient solution using the find() method, which operates in C. Here's the improved code:
def occurrences(string, sub): count = start = 0 while True: start = string.find(sub, start) + 1 if start > 0: count+=1 else: return count
How it Works
Usage Example
For example, counting the occurrences of "11" in the string "1011101111" using this method would yield the same result of 5, but with improved efficiency.
The above is the detailed content of How Can I Efficiently Count Overlapping String Occurrences in Python?. For more information, please follow other related articles on the PHP Chinese website!