python – Count number of occurrences of a substring in a string

python – Count number of occurrences of a substring in a string

string.count(substring), like in:

>>> abcdabcva.count(ab)
2

Update:

As pointed up in the comments, this is the way to do it for non overlapping occurrences. If you need to count overlapping occurrences, youd better check the answers at: Python regex find all overlapping matches?, or just check my other answer below.

s = arunununghhjj
sb = nun
results = 0
sub_len = len(sb)
for i in range(len(s)):
    if s[i:i+sub_len] == sb:
        results += 1
print results

python – Count number of occurrences of a substring in a string

Depending what you really mean, I propose the following solutions:

  1. You mean a list of space separated sub-strings and want to know what is the sub-string position number among all sub-strings:

    s = sub1 sub2 sub3
    s.split().index(sub2)
    >>> 1
    
  2. You mean the char-position of the sub-string in the string:

    s.find(sub2)
    >>> 5
    
  3. You mean the (non-overlapping) counts of appearance of a su-bstring:

    s.count(sub2)
    >>> 1
    s.count(sub)
    >>> 3
    

Leave a Reply

Your email address will not be published.