Open In App
Related Articles

Python | Count occurrences of a character in string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a string, the task is to count the frequency of a single character in that string using Python. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters. 

Example

Input:'GeeksForGeeks'
Output:'4'
Explanation: In this, we have counted the occurrence of 'e' in the string.

Count occurrences of a character in String

We can count occurrences of a character in a string using different methods. Here are the different methods we can use to count the occurrences of a character in a string are listed below:

  • Using Native Method
  • Using Count() Method
  • Using Collections.Counter() Method
  • Using Lambda Functions
  • Using Regular Expressions
  • Using Operator.countOf() Method
  • Using Reduce() Method

Python Program to Count Occurrence of a Character in a String using Native Method

Naive method Iterate the entire string for that particular character and then increase the counter when we encounter the particular character. 

Python3

# initializing string
test_str = "GeeksforGeeks"
 
# using naive method to get count
# counting e
count = 0
 
for i in test_str:
    if i == 'e':
        count = count + 1
 
# printing result
print("Count of e in GeeksforGeeks is : "
      + str(count))

                    

Output

Count of e in GeeksforGeeks is : 4

Time Complexity: O(n), where n is the length of string test_str.
Auxiliary Space: O(1), where an additional count variable is used to store the result.

Count Number of Occurrences in a String with .count()

Using count() is the most conventional method in Python to get the occurrence of any element in any container. This is easy to code and remember and hence quite popular. 

Python3

# initializing string
test_str = "GeeksforGeeks"
 
# using count() to get count of "e"
counter = test_str.count('e')
 
# printing result
print("Count of e in GeeksforGeeks is : "
      + str(counter))

                    

Output

Count of e in GeeksforGeeks is : 4

Time Complexity: O(n)
Auxiliary Space: O(n)

Count Number of Occurrences in a Python String with Counter

Using collections.Counter() method, is used to get the occurrence of the element across any container in Python. This also performs the task similar to the above two methods, just is a function of a different library i.e collections. This is the lesser-known method

Python3

from collections import Counter
 
# initializing string
test_str = "GeeksforGeeks"
 
# using collections.Counter() to get count
# counting e
count = Counter(test_str)
 
# printing result
print("Count of e in GeeksforGeeks is : "
      + str(count['e']))

                    

Output

Count of e in GeeksforGeeks is : 4

Time Complexity: O(n) (Linear time complexity)
Auxiliary Space: O(k) (where k is the number of distinct characters)

Count Number of Occurrences in a Python String using Lambda

Using lambda + sum() + map() Lambda functions, along with sum() and map() can achieve this particular task of counting the total occurrences of particular element in a string. This uses sum() to sum up all the occurrences obtained using map(). 

Python3

# initializing string
test_str = "GeeksforGeeks"
 
# using lambda + sum() + map() to get count
# counting e
count = sum(map(lambda x: 1 if 'e' in x else 0, test_str))
 
# printing result
print("Count of e in GeeksforGeeks is : "
      + str(count))

                    

Output

Count of e in GeeksforGeeks is : 4

Time Complexity: O(n) (Linear time complexity)
Auxiliary Space: O(1) (Constant Space complexity)

Count Number of Occurrences in a Python String using Regular Expressions

Using re + findall() Regular Expressions can help us to achieve many coding tasks related to strings. They can also facilitate us in achieving the task of finding the occurrence of an element in a string. 

Python3

# Python3 code to demonstrate
# occurrence frequency using
# re + findall()
import re
 
# initializing string
test_str = "GeeksforGeeks"
 
# using re + findall() to get count
# counting e
count = len(re.findall("e", test_str))
 
# printing result
print("Count of e in GeeksforGeeks is : "
      + str(count))

                    

Output

Count of e in GeeksforGeeks is : 4

Time Complexity: O(n)
Auxiliary Space: O(n)

Count the Number of Occurrences in a Python String using Operator.countOf() Method

Using operator.Countof() method, is used for counting the number of occurrence of b in a. occurrencesIt counts the number of occurrences of value.

Python3

import operator as op
# initializing string
test_str = "GeeksforGeeks"
 
# using operator.countOf() to get count
# counting e
counter = op.countOf(test_str, "e")
 
# printing result
print("Count of e in GeeksforGeeks is : "
      + str(counter))

                    

Output

Count of e in GeeksforGeeks is : 4

Time Complexity: O(n)
Auxiliary Space: O(1)

Count Number of Occurrences in a Python String using Reduce() Method

To count the occurrences of a character in a string using the reduce() method, you can use lambda functions. Define a lambda function that takes two arguments: an accumulator acc and a character c. The lambda function checks if the current character c is equal to the character to count char_to_count. Apply the reduce() function to the input string test_str, using the lambda function and an initial value of 0. The reduce() function applies the lambda function to each character in the string test_str, starting with the initial value 0. The final value of the accumulator acc is the count of the character char_to_count in the string test_str. The result is stored in the count variable. Print the result using an f-string to format the output.

Python3

from functools import reduce
 
# initializing string
test_str = "GeeksforGeeks"
char_to_count = 'e'
 
# using reduce to get count
count = reduce(lambda acc, c: acc + 1 if c ==
               char_to_count else acc, test_str, 0)
 
# printing result
print(f"Count of {char_to_count} in {test_str} is: {count}")
# This code is contributed by Vinay Pinjala.

                    

Output

Count of e in GeeksforGeeks is : 4

The time complexity of this code is O(n), where n is the length of the input string test_str. This is because we iterate over each character in the string exactly once.

The auxiliary space of this code is O(1) because we only use a constant amount of additional space to store the input string, the character to count, the accumulator acc, and the lambda function. Therefore, the space used does not depend on the length of the input string.



Last Updated : 11 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads