Home > Backend Development > Python Tutorial > How Can I Efficiently Count Substring Occurrences in Python (Including Overlapping Cases)?

How Can I Efficiently Count Substring Occurrences in Python (Including Overlapping Cases)?

Barbara Streisand
Release: 2024-11-28 21:47:10
Original
963 people have browsed it

How Can I Efficiently Count Substring Occurrences in Python (Including Overlapping Cases)?

Counting Occurrences of a Substring within a String in Python

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template