Reputation: 372
I have a string
string = 'AAA'
When using the string.count('A')
the output is equal to 3
and if it is string.count('AA')
the output is equal to 1
However, there are 2 'AA's in the string.
Is there any method to count repeated string like above by using dictionary function?
I'd like to hear your helpful suggestions.
Thank you all in advance.
Upvotes: 1
Views: 6869
Reputation: 53
Yeah! You can use a dictionary
def count(input):
a = {}
for i in input:
a[i] = a.get(i,0)+ 1
return a
print(count('AA')) #Would return 2
Upvotes: -1
Reputation: 13776
Alternative for "not huge" strings
>>> s, sub = 'AAA', 'AA'
>>> sum(s[x:].startswith(sub) for x in range(len(s)))
2
I find this a little more readable.
Upvotes: 1
Reputation: 7929
The problem is Count return the number of (non-overlapping) occurrences of substring sub in string.
try this as you can see at this post:
def occurrences(string, sub):
count = start = 0
while True:
start = string.find(sub, start) + 1
if start > 0:
count+=1
else:
return count
Upvotes: 1