简体   繁体   中英

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.

Why not use the count method of str ?

>>> a = "abcghabchjlababc"
>>> a.count("abc")
3

Another possible solution.

>>> a= 'almforeachalmwhilealmleandroalmalmalm'
>>> len(a.split('alm')) - 1
6
>>> q = "abcghabchjlababc"
>>> len(q.split("abc")) - 1
3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM