Count Occurrences of a Character in a String in Python

Count Occurrences of a Character in a String in Python

Hiten Kanwar Jul-18, 2021 Jun-02, 2021 Python Python String
  1. Use the count() Function to Count the Number of a Characters Occuring in a String in Python
  2. Use the collections.Counter to Count the Occurrences of a Character in a String in Python
  3. Use Regular Expressions to Count the Occurrences of a Character in a String in Python
  4. Use the defaultdict to Count the Occurrences of a Character in a String in Python
  5. Use the pandas.value_counts() to Count the Occurrences of a Character in a String in Python
  6. Use a lambda Expression to Count the Occurrences of a Character in a String in Python
  7. Use the for Loop to Count the Occurrences of a Character in a String in Python

In Programming, a string is a sequence of characters.

This tutorial will introduce how to count the number of occurrences of a character in a String in Python.

Use the count() Function to Count the Number of a Characters Occuring in a String in Python

We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.

For example,

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

Output:

4

Remember, upper and lower cases are treated as different characters. A and a will be treated as different characters and have different counts.

Use the collections.Counter to Count the Occurrences of a Character in a String in Python

A Counter is a dictionary subclass present in the collections module. It stores the elements as dictionary keys, and their occurrences are stored as dictionary values. Instead of raising an error, it returns a zero count for missing items.

For example,

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

Output:

4

It is a better choice when counting for many letters as counter calculates all the counts one time. It is a lot faster than the count() function.

Use Regular Expressions to Count the Occurrences of a Character in a String in Python

A regular expression is a specialized syntax held in a pattern that helps find the strings or set of strings by matching that pattern. We import the re module to work with regular expressions.

We can use the findall() function for our problem.

For example,

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

Output:

4

Use the defaultdict to Count the Occurrences of a Character in a String in Python

Defaultdict is present in the collections module and is derived from the dictionary class. Its functionality is relatively the same as that of dictionaries except that it never raises a KeyError, as it provides a default value for the key that never exists.

We can use it to get the occurrences of a character in a string as shown below.

from collections import defaultdict

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

for char in text:
    chars[char] += 1
    
print(chars['a'])
print(chars['t'])
print(chars['w']) # element not present in the string, hence print 0

Output:

4
2
0

Use the pandas.value_counts() to Count the Occurrences of a Character in a String in Python

We can use the pandas.value_counts() method to get the occurrences of all the characters present in the provided string. We need to pass the string as a Series object.

For example,

import pandas as pd
phrase = "Mary had a little lamb"
print(pd.Series(list(phrase)).value_counts())

Output:

     4
a    4
l    3
t    2
e    1
b    1
h    1
r    1
y    1
M    1
m    1
i    1
d    1
dtype: int64

It returns the occurrences of all characters in a Series object.

Use a lambda Expression to Count the Occurrences of a Character in a String in Python

lambda functions can not only count occurrences from the given string, but can also work when we have the string, as a list of sub-strings.

See the following code.

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

Output:

4

Use the for Loop to Count the Occurrences of a Character in a String in Python

We iterate over the string, and if the element equals the desired character, the count variable is incremented till we reach the end of the string.

For example,

sentence = 'Mary had a little lamb'    
count = 0
for i in sentence:
    if i == "a":
        count = count + 1
print(count)

Output:

4

We can see another way of using this method with the sum() function can be seen below.

my_string = "Mary had a little lamb"
print(sum(char == 'a' for char in my_string))

Output:

4

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python