#### [SOLVED] Count the number occurrences of a character in a string

By Mat

What's the simplest way to count the number of occurrences of a character in a string?

e.g. count the number of times `'a'` appears in `'Mary had a little lamb'`

#### @Dipen Bakraniya 2019-09-07 20:16:48

Python 3

Ther are two ways to achieve this:

1) With built-in function count()

``````sentence = 'Mary had a little lamb'
print(sentence.count('a'))`
``````

2) Without using a function

``````sentence = 'Mary had a little lamb'
count = 0

for i in sentence:
if i == "a":
count = count + 1

print(count)
``````

#### @Brenden Brown 2012-08-01 22:12:08

As other answers said, using the string method count() is probably the simplest, but if you're doing this frequently, check out collections.Counter:

``````from collections import Counter
my_str = "Mary had a little lamb"
counter = Counter(my_str)
print counter['a']
``````

#### @meshy 2015-02-10 22:36:35

Why is this better when used frequently? What is the advantage?

#### @Brenden Brown 2015-02-17 19:30:20

If you want the counts for a lot of the letters in a given string, Counter provides them all in a more succinct form. If you want the count for one letter from a lot of different strings, Counter provides no benefit.

#### @Daniel B. 2015-07-20 17:58:45

For this particular instance, counting characters, I would prefer collections.counter. For finding instances of a specific substring, I would use a regular expression or the str.count() method. I haven't tested, but there may be a performance difference due to a slight overhead in counting all characters and appending to a dictionary rather than counting occurrences of a single substring. I would suggest writing a script to generate a very long file to search and then timing execution of each method.

#### @BAMF4bacon 2016-05-31 14:32:52

The advantage when used frequently is that Counter calculates all the counts ONE TIME, which is almost as fast as doing mystring.count('a') one time. Thus, if you do this 20 times, you are saving maybe 10 times the computation time. Counter also can tell you if an item is in the string: for example, if 'a' in counter:

#### @Syed Shamikh Shabbir 2019-03-07 09:04:22

An alternative way to get all the character counts without using `Counter()`, `count` and regex

``````counts_dict = {}
for c in list(sentence):
if c not in counts_dict:
counts_dict[c] = 0
counts_dict[c] += 1

for key, value in counts_dict.items():
print(key, value)
``````

#### @Carlson Bimbuh 2018-08-21 22:04:22

Using Count:

``````string = "count the number of counts in string to count from."
x = string.count("count")
``````

x = 3.

#### @datapug 2019-01-11 01:15:36

In the example above x is equal 3.

#### @Nuno André 2016-10-02 02:33:10

`str.count(a)` is the best solution to count a single character in a string. But if you need to count more characters you would have to read the whole string as many times as characters you want to count.

A better approach for this job would be:

``````from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict(int)

for char in text:
chars[char] += 1
``````

So you'll have a dict that returns the number of occurrences of every letter in the string and `0` if it isn't present.

``````>>>chars['a']
4
>>>chars['x']
0
``````

For a case insensitive counter you could override the mutator and accessor methods by subclassing `defaultdict` (base class' ones are read-only):

``````class CICounter(defaultdict):
def __getitem__(self, k):
return super().__getitem__(k.lower())

def __setitem__(self, k, v):
super().__setitem__(k.lower(), v)

chars = CICounter(int)

for char in text:
chars[char] += 1

>>>chars['a']
4
>>>chars['M']
2
>>>chars['x']
0
``````

#### @merv 2017-10-30 21:29:48

You're basically reimplementing `Counter`, which is already a class in `collections`.

#### @Nuno André 2017-11-09 10:42:22

@merv Not really. `Counter` is a more bloated pure Python class and `defaultdict`'s `__missing__` is written in C. For a simple task like this (`int` is also implemented in C) this approach is sligthly faster.

#### @Erick Mwazonga 2018-03-20 13:19:17

This easy and straight forward function might help:

``````def check_freq(str):
freq = {}
for c in str:
freq[c] = str.count(c)
return freq

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}
``````

#### @Nuno André 2019-03-17 21:47:59

You're shadowing `str`. If you give its name to the variable, `str` is not a built-in type anymore. Also you are counting fourteen b's fourteen times. You can avoid that simply by changing `for c in text` with `for c in set(text)`.

#### @B-Y 2015-01-11 17:24:27

"Without using count to find you want character in string" method.

``````import re

def count(s, ch):

pass

def main():

s = raw_input ("Enter strings what you like, for example, 'welcome': ")

ch = raw_input ("Enter you want count characters, but best result to find one character: " )

print ( len (re.findall ( ch, s ) ) )

main()
``````

#### @bugmenot123 2017-08-09 08:04:43

Why the empty count function? Why the main() function? Why the ugly spaces everywhere? This is NOT a good answer.

#### @Satish Garg 2017-03-28 17:13:33

`count` is definitely the most concise and efficient way of counting the occurrence of a character in a string but I tried to come up with a solution using `lambda`, something like this :

``````sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
``````

This will result in :

``````4
``````

Also, there is one more advantage to this is if the sentence is a list of sub-strings containing same characters as above, then also this gives the correct result because of the use of `in`. Have a look :

``````sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
``````

This also results in :

``````4
``````

But Of-course this will work only when checking occurrence of single character such as `'a'` in this particular case.

#### @abhishek narayan 2017-01-22 08:37:33

This will give you the occurrence of each characters in a string. O/P is also in string format:

``````def count_char(string1):
string2=""
lst=[]
lst1=[]
for i in string1:
count=0
if i not in lst:
for j in string1:
if i==j:
count+=1
lst1.append(i)
lst1.append(count)
lst.append(i)

string2=''.join(str(x) for x in lst1)
return string2

print count_char("aabbacddaabbdsrchhdsdg")
``````

#### @Ogre Codes 2009-07-20 20:04:26

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring `sub` in the range `[start, end]`. Optional arguments `start` and `end` are interpreted as in slice notation.

``````>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
``````

#### @eduffy 2009-07-20 20:04:45

You can use count() :

``````>>> 'Mary had a little lamb'.count('a')
4
``````

#### @Thiru G 2016-04-01 01:29:24

``````str = "count a character occurance"

List = list(str)
print (List)
Uniq = set(List)
print (Uniq)

for key in Uniq:
print (key, str.count(key))
``````

#### @Tim Seed 2016-02-23 19:16:31

No more than this IMHO - you can add the upper or lower methods

``````def count_letter_in_str(string,letter):
return string.count(letter)
``````

#### @rookie 2015-11-15 19:05:09

``````spam = 'have a nice day'
var = 'd'

def count(spam, var):
found = 0
for key in spam:
if key == var:
found += 1
return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))
``````

#### @rookie 2015-10-24 22:36:58

``````a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
print key, a.count(key)
``````

#### @jafelds 2014-12-05 17:04:28

Regular expressions are very useful if you want case-insensitivity (and of course all the power of regex).

``````my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))
``````

Be aware that the regex version takes on the order of ten times as long to run, which will likely be an issue only if my_string is tremendously long, or the code is inside a deep loop.

#### @Ogre Codes 2016-08-17 05:31:23

Regex is overkill if you are just trying to fix case sensitivity. my_sting.lower().count('m') is more performant, more clear, and more succinct.

#### @Aaron Fi 2009-07-20 20:05:03

``````"aabc".count("a")
``````

#### @Finer Recliner 2009-07-20 20:04:47

``````myString.count('a');
``````

#### @Sinan Taifour 2009-07-20 20:03:19

Regular expressions maybe?

``````import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
``````

#### @nilamo 2009-07-20 20:18:02

A fine idea, but overkill in this case. The string method 'count' does the same thing with the added bonus of being immediately obvious about what it is doing.

#### @kiltek 2012-03-31 10:18:17

why negative rate, maybe someone needs this kind of code for something similar. my vote up

#### @Christopher 2013-10-21 18:04:55

This should be downvoted because it is the least efficient way possible to count characters in a string. If the goal is simply to count characters, as the question indicates, it would be hard to find a worse way to do the job. In terms of memory and processor overhead, this solution is definitely to be avoided. No one will ever "need" to use this method to find the count of characters in a string.

#### @Speccy 2013-10-28 20:14:54

@kiltek Indeed, this little snippet has been useful to me with a regular expression a bit more complex

#### @Conor 2016-06-23 08:48:45

good solution when string methods are not available: `len(re.findall('1',bin(10)))`

### [SOLVED] How can I count the occurrences of a list item?

• 2010-04-08 13:30:00
• weakish
• 1522280 View
• 1422 Score
• Tags:   python list count

### [SOLVED] How do I count the number of occurrences of a char in a String?

• 2008-11-09 14:07:09
• Bart
• 839233 View
• 515 Score
• Tags:   java string

### [SOLVED] Count the number of occurrences of a character in a string in Javascript

• 2009-05-19 05:24:24
• Akash
• 553389 View
• 471 Score