Python中计算另一个字符串中的字符串的更好方法


问题内容

这段代码有效,但是在这里阅读文章后,我得到的印象可能不是一个非常“ Pythonic”的解决方案。有没有更好,更有效的方法来解决此特定问题:

这段代码的作用:它计算在另一个字符串中找到的一个字符串的实例,然后返回计数。如果用户尝试传递空字符串,则会引发错误。

我想出了代码的版本,但想知道是否有更好,更有效的“ Pythonic”方法来做到这一点:

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

这段代码是用Python 2.7编写的,但是应该可以在3.x版本中使用。


问题答案:

为什么不使用count方法str

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