Count number of occurrences of a given substring in a string

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

    Below logic will work for all string & special characters

    def cnt_substr(inp_str, sub_str):
        inp_join_str = ''.join(inp_str.split())
        sub_join_str = ''.join(sub_str.split())
    
        return inp_join_str.count(sub_join_str)
    
    print(cnt_substr("the sky is   $blue and not greenthe sky is   $blue and not green", "the sky"))
    

提交回复
热议问题