Number of occurrences of a substring in a string

前端 未结 6 1555
死守一世寂寞
死守一世寂寞 2020-12-12 04:08

I need to count the nunber of times the substring \'bob\' occurs in a string.

Example problem: Find the number of times \'bob\' occurs in string s such

6条回答
  •  不思量自难忘°
    2020-12-12 04:54

    For this job, str.find isn't very efficient. Instead, str.count should be what you use:

    >>> s = 'xyzbobxyzbobxyzbob'
    >>> s.count('bob')
    3
    >>> s.count('xy')
    3
    >>> s.count('bobxyz')
    2
    >>>
    

    Or, if you want to get overlapping occurrences, you can use Regex:

    >>> from re import findall
    >>> s = 'bobobob'
    >>> len(findall('(?=bob)', s))
    3
    >>> s = "bobob"
    >>> len(findall('(?=bob)', s))
    2
    >>>
    

提交回复
热议问题