Count number of occurrences of a given substring in a string

后端 未结 30 2001
不思量自难忘°
不思量自难忘° 2020-11-22 13:58

How can I count the number of times a given substring is present within a string in Python?

For example:

>>> \'foo bar foo\'.numberOfOccurre         


        
30条回答
  •  一个人的身影
    2020-11-22 14:54

    How about a one-liner with a list comprehension? Technically its 93 characters long, spare me PEP-8 purism. The regex.findall answer is the most readable if its a high level piece of code. If you're building something low level and don't want dependencies, this one is pretty lean and mean. I'm giving the overlapping answer. Obviously just use count like the highest score answer if there isn't overlap.

    def count_substring(string, sub_string):
        return len([i for i in range(len(string)) if string[i:i+len(sub_string)] == sub_string])
    

提交回复
热议问题