How to real count repeated string in string in python?

Question:

I am sorry that I am not sure my question is correct or clear enough. However, I hope the example below can explain my question:

As what you see
print("abbbbbbc".count("bbb")) #–output is 2

But I want the result is 4, because bbbbbb has 6 characters and can breakdown as below:

bbb—

-bbb–

–bbb-

—bbb

I couldn’t figure out which function I can use to solve this matter. What I did is count by for combinations, and it doesn’t look right at all.

Thank for helping.

Asked By: Tut

||

Answers:

You can implement your own logic, like this:

a = "abbbbbbc"
b = "bbb"

count = 0
for i in range(len(a) - len(b)):
    if a[i:i+len(b)] == b:
        count += 1
print(count)

OR

count = 0
for i in range(len(a)):
    if a[i:].startswith(b):
        count += 1
print(count)

OR

count = sum([1 if a[i:].startswith(b) else 0 for i in range(len(a))])
print(count)
Answered By: Ivan Perehiniak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.