Count number of occurrences of a given substring in a string

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

    The question isn't very clear, but I'll answer what you are, on the surface, asking.

    A string S, which is L characters long, and where S[1] is the first character of the string and S[L] is the last character, has the following substrings:

    • The null string ''. There is one of these.
    • For every value A from 1 to L, for every value B from A to L, the string S[A]..S[B] (inclusive). There are L + L-1 + L-2 + ... 1 of these strings, for a total of 0.5*L*(L+1).
    • Note that the second item includes S[1]..S[L], i.e. the entire original string S.

    So, there are 0.5*L*(L+1) + 1 substrings within a string of length L. Render that expression in Python, and you have the number of substrings present within the string.

提交回复
热议问题