Count number of occurrences of a given substring in a string

后端 未结 30 2135
不思量自难忘°
不思量自难忘° 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:51

    Scenario 1: Occurrence of a word in a sentence. eg: str1 = "This is an example and is easy". The occurrence of the word "is". lets str2 = "is"

    count = str1.count(str2)
    

    Scenario 2 : Occurrence of pattern in a sentence.

    string = "ABCDCDC"
    substring = "CDC"
    
    def count_substring(string,sub_string):
        len1 = len(string)
        len2 = len(sub_string)
        j =0
        counter = 0
        while(j < len1):
            if(string[j] == sub_string[0]):
                if(string[j:j+len2] == sub_string):
                    counter += 1
            j += 1
    
        return counter
    

    Thanks!

提交回复
热议问题