Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way in Python to count string in another string

This code works, but reading posts on here I get the impression it is probably not a very "Pythonic" solution. Is there a better more efficient way to solve this specific problem:

What this code does: it counts instances of one string found in another and return the count. It raises an error in case the user tries to pass in an empty string.

The version of the code I came up with but wondering if there is a better more efficient more "Pythonic" way to do this:

def count_string(raw_string, string_to_count):
    if len(string_to_count) == 0:
        raise ValueError("The length of string_to_count should not be 0!")
    else:
        str_count = 0
        string_to_count = string_to_count.lower()
        raw_string = raw_string.lower()
        if string_to_count not in raw_string:
            # this causes early exit if string not found at all
            return str_count
        else:
            while raw_string.find(string_to_count) != -1:
                indx = raw_string.find(string_to_count)
                str_count += 1
                raw_string = raw_string[(indx+1): ]
            return str_count

This code was written in Python 2.7 but should work in 3.x.

like image 209
TMWP Avatar asked Mar 07 '26 22:03

TMWP


1 Answers

Why not use the count method of str?

>>> a = "abcghabchjlababc"
>>> a.count("abc")
3
like image 135
Uriel Avatar answered Mar 09 '26 11:03

Uriel