Count number of occurrences of a given substring in a string

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

    I'm not sure if this is something looked at already, but I thought of this as a solution for a word that is 'disposable':

    for i in xrange(len(word)):
    if word[:len(term)] == term:
        count += 1
    word = word[1:]
    
    print count
    

    Where word is the word you are searching in and term is the term you are looking for

提交回复
热议问题