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.
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)
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.
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)