Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to real count repeated string in string in python?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading