DEV Community

oladejo abdullahi
oladejo abdullahi

Posted on

Count occurrences of a character in string

How to count occurrences of a character in string

let say you were given a string and the task is to count the frequency of a single character in that string. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters. Here I am going to show you different ways of doing that.

Method 1 : Naive method

just loop through the entire string for that particular character and then increase the counter when we meet the character.

Example

you were given a variable test_string storing "allAlphabets" you were to count the number of 'l' in the string.
Here is the codes:

test_string = "allAlphabets"      
count = 0
for i in test_string: 
    if i == 'l': 
        count = count + 1  
print ("the number of l in allAlphabets is :", count) 
Enter fullscreen mode Exit fullscreen mode

Output :

the number of l in allAlphabets is : 3
Enter fullscreen mode Exit fullscreen mode

you can substitute with any other letter you like. you can read more on this method here

Method 2 : Using count()

Using count() is the easiest method in Python to get the occurrence of any element in any container or character in a string. This is easy to code and remember. the formular to count character in string with this method is
string.count('character')
Let's try to use this method to solve the same problem.

test_string="allAlphabets" 
# Now we need to count the number of l
counter = test_string.count('l')   
print ("the number of l in allAlphabets is : ",counter) 
Enter fullscreen mode Exit fullscreen mode

Output :

the number of l in allAlphabets is : 3
Enter fullscreen mode Exit fullscreen mode

Method3 : Using collections.Counter()

This method is not common but it also calculate the occurrence of the element across any container in Python. The way it works is similar to above two method.
Let's see how to use it to solve the same question
from collections import Counter#we need to import counter function.

from collections import Counter
test_string = "allAlphabets"
count = Counter(test_string)
#Counter() is a function that count from parameter in it.   
print ("Count of l in allAlphabets is : ",count['l'])
Enter fullscreen mode Exit fullscreen mode

Output :

Count of l in allAlphabets is :  3
Enter fullscreen mode Exit fullscreen mode

did you get it? this is the formula to illustrate it below
from collections import Counter
variableForCounting = Counter(container or string)
Num_ofCharacter = variableForCounting['character'].
Now from the above method you can use any of the one you think the best. enjoy!

Top comments (0)