-2

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.

Tut
  • 59
  • 6

1 Answers1

1

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)
  • Thanks, I found the answers from the suggestion above with overlapping count. However, you answers are also great! – Tut Dec 02 '22 at 15:42