Better way in Python to count string in another string

↘锁芯ラ 提交于 2019-12-19 10:05:48

问题


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.


回答1:


Why not use the count method of str?

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



回答2:


Another possible solution.

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


来源:https://stackoverflow.com/questions/42765930/better-way-in-python-to-count-string-in-another-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!