0

I want to find the number of occurrences of a particular sub-string in a string.

string="abcbcbcb"
sub_str="cbc"
c=string.count(sub_str)
print(c)

This gives the output as

1

which is the number of non-overlapping occurrences of substring in the string. But I want to calculate the overlapping strings as well. Thus, the desired output is:

2
1

2 Answers 2

2

You can use a regular expression, use module "re"

print len(re.findall('(?=cbc)','abcbcbcb'))
Sign up to request clarification or add additional context in comments.

1 Comment

This is showing error. But upon improvements it works,thanks!@Sergey Chinkov
0

No standard function available for overlapping count. You could write custom function tho.

def count_occ(string, substr):
   cnt = 0
   pos = 0
   while(True):
       pos = string.find(substr , pos)
       if pos > -1:
           cnt += 1
           pos += 1
       else:
           break
   return cnt


string="abcbcbcb"
sub_str="cbc"
print(count_occ(string,sub_str))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.