Home >Backend Development >Python Tutorial >How Can I Efficiently Count Substring Occurrences in Python (Including Overlapping Cases)?
A frequent programming task involves determining the number of times a specific substring appears within a larger string. Python provides several methods to efficiently accomplish this task.
One straightforward approach is to utilize the string.count() method. This method takes the substring as an argument and returns the number of occurrences within the string. For instance:
>>> 'foo bar foo'.count('foo') 2
This method also counts two consecutive overlapping occurrences of the substring. If this is undesirable, you can consider other options.
If you need to account for overlapping occurrences, a custom implementation using a sliding window approach can be employed. Here's an example:
def count_overlapping_occurrences(string, substring): count = 0 window_start = 0 window_end = len(substring) while window_end <= len(string): substring_occurrence = string[window_start:window_end] if substring_occurrence == substring: count += 1 window_start += 1 window_end += 1 return count >>> count_overlapping_occurrences('abcdabcva', 'ab') 4
By using this function, you can accurately determine the number of occurrences of a substring within a string, regardless of whether they overlap.
The above is the detailed content of How Can I Efficiently Count Substring Occurrences in Python (Including Overlapping Cases)?. For more information, please follow other related articles on the PHP Chinese website!