By Mat

2009-07-20 20:00:36 8 Comments

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'


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

This easy and straight forward function might help:

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

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

@Sébastien Wieckowski 2020-01-19 09:23:50

I am a fan of the pandas library, in particular the value_counts() method. You could use it to count the occurrence of each character in your string:

>>> import pandas as pd
>>> phrase = "I love the pandas library and its `value_counts()` method"
>>> pd.Series(list(phrase)).value_counts()
a    5
e    4
t    4
o    3
n    3
s    3
d    3
l    3
u    2
i    2
r    2
v    2
`    2
h    2
p    1
b    1
I    1
m    1
(    1
y    1
_    1
)    1
c    1
dtype: int64

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



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.

@Dipen Gajjar 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'

2) Without using a function

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

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


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

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


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


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

@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):


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


@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 :


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 :


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

@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')

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

You can use count() :

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

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

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


more info here

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

Related Questions

Sponsored Content

24 Answered Questions

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

  • 2010-04-08 13:30:00
  • weakish
  • 1712703 View
  • 1539 Score
  • 24 Answer
  • Tags:   python list count

26 Answered Questions

[SOLVED] How to count string occurrence in string?

45 Answered Questions

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

  • 2008-11-09 14:07:09
  • Bart
  • 871686 View
  • 552 Score
  • 45 Answer
  • Tags:   java string

66 Answered Questions

[SOLVED] How to replace all occurrences of a string?

32 Answered Questions

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

  • 2009-05-19 05:24:24
  • Akash
  • 629215 View
  • 530 Score
  • 32 Answer
  • Tags:   javascript string

3 Answered Questions

64 Answered Questions

[SOLVED] What is the difference between String and string in C#?

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

24 Answered Questions

[SOLVED] How to check if the string is empty?

21 Answered Questions

Sponsored Content