Count of a character in a string in Python?

Ways to find the count of a character in string in Python

We will discuss how to find the count of a character in string in Python.

The count() function returns the count of a substring in a string by passing the character within the function.

To find the count of a character in string in Python.

  1. Use the count() function.

See the code below.

# Count of a character in string in Python
import re
string = "educatepython"
count = string.count('e')
print(count)  
# Output: 2

We can also use regular expressions to count the occurrence of a character in string in Python.

The re module provides the tools to use regular expressions in Python. We can use the findall() function that returns all the matching occurrences of a substring in string. Then, we can use the len() function to get the total count of the substring.

To find the count of a character in string in Python.

  1. Use the re.findall() function to find all occurrences of the character.
  2. Use the len() function to count the occurrence of a character in a string in Python.

See the code below.

# Count of a character in string in Python
import re
string = "educatepython"
count = len(re.findall('e',string))
print(count)  
# Output: 2

The collections module provides an additional set of alternative datatypes in Python. The collections.Counter stores the elements from an iterable in a dictionary. The elements are the keys and their count is their values.

To find the count of a character in string in Python.

  1. Use the collections.Counter object.

See the code below.

# Count the occurrence of a character in string in Python
import collections
string = "educatepython"
count = collections.Counter(string)
print(count['e'])  
# Output: 2    

The base class of the collections.Counter object is the dict class which represents dictionaries.

Alternatively, we can also use the for loop. Using this loop, we compare each character individually and increment a counter variable based on the match.

To find the count of a character in string in Python.

  1. Use the for loop to iterate over the string.
  2. Compare each character with the required character.
  3. Increment a counter variable when the match returns True.

See the code below.

# Count of a character in string in Python
string = "educatepython"
count = 0
for i in string:
    if i=='e':
        count = count + 1
print(count)  
# Output: 2    

To conclude.

This tutorial demonstrated several methods to find the count of a character in string in Python. The count() function is the most direct method to achieve this. We can also use the re module which is demonstrated in the following method. The collections.Counter object can also achieve this. Alternatively, we can follow a traditional exhaustive approach using the for loop as well.

Explore more from this category at Python Strings. Alternatively, search and view other topics at All Tutorials.