Determining how many times a substring occurs in a string in Python

Viewed 116274

I am trying to figure out how many times a string occurs in a string. For example:

nStr = '000123000123'

Say the string I want to find is 123. Obviously it occurs twice in nStr but I am having trouble implementing this logic into Python. What I have got at the moment:

pattern = '123'
count = a = 0
while pattern in nStr[a:]:
    a = nStr[a:].find(pattern)+1
    count += 1
return count

The answer it should return is 2. I'm stuck in an infinite loop at the moment.

I was just made aware that count is a much better way to do it but out of curiosity, does anyone see a way to do it similar to what I have already got?

13 Answers

In case you are searching how to solve this problem for overlapping cases.

s = 'azcbobobegghaklbob'
str = 'bob'
results = 0
sub_len = len(str) 
for i in range(len(s)):
    if s[i:i+sub_len] == str: 
        results += 1
print (results)

Will result in 3 because: [azc(bob)obegghaklbob] [azcbo(bob)egghaklbob] [azcbobobegghakl(bob)]

I'm pretty new, but I think this is a good solution? maybe?

def count_substring(str, sub_str):
    count = 0
    for i, c in enumerate(str):
        if sub_str == str[i:i+2]:
            count += 1
    return count
def count_substring(string, substring):
         c=0
         l=len(sub_string)
         for i in range(len(string)):
                 if string [i:i+l]==sub_string:
                          c=c+1
         return c
string=input().strip()
sub_string=input().strip()

count= count_substring(string,sub_string)
print(count)

As mentioned by @João Pesce and @gaurav, count() is not useful in the case of overlapping substrings, try this out...

def count_substring(string, sub_string):
    c=0
    for i in range(len(string)):
        if(string[i:i+len(sub_string)]==sub_string):
            c = c+1
    return c
def countOccurance(str,pat):
    count=0
    wordList=str.split()
    for word in wordList:
        if pat in word:
            count+=1
    return count

Usually i'm using enumerate for this kind of problems:

def count_substring(string, sub_string):
        count = 0
        for i, j in enumerate(string):
            if sub_string in string[i:i+3]:
                count = count + 1
        return count

def count(sub_string,string):

count = 0
ind = string.find(sub_string)

while True:
    if ind > -1:
        count += 1
        ind = string.find(sub_string,ind + 1)
    else:
        break
return count
def count_substring(string, sub_string):
    count = 0
    len_sub = len(sub_string)
    for i in range(0,len(string)):
        if(string[i:i+len_sub] == sub_string):
            count+=1
    return count
Related