Count Occurrences of Character in String in Python

Using count() Method

Use String’s count() method to count occurrences of character in String in Python e.g. my_string.count(character). count() method returns number of occurrences of the character in String.

We will get the following result after running the above program.

The count() is a conventional method in Python. It holds a substring, start, and end as arguments and returns the count of appearances of any element in an iterable object. We used the count() method to count the occurrences of the character in my_String.

Using Naive for loop

To count the occurrences of a character in a string in Python:

  • Use for loop to iterate over each character of input String.
  • For each character, use the if statement to check if supplied character appears in String.
  • Increment the count by 1 if character exists in String.

We will get the below output on the successful execution of the above program.

We used for loop to iterate over every element in my_string.

We incremented the count by 1 when the character appeared in my_string using an if statement.

Using List Comprehension

To calculate the occurrences of a character in a string in Python:

  • Use for loop to iterate every character of input string.
  • Append the element to a new list if the required character appears in string.
  • Use the len() method to find the occurrence of the character in string.

The code above will print the following output on the console:

List Comprehension is a static construct for creating lists using a concise notation to make code more readable and efficient. It takes an existing iterable object and applies an expression, filter, or function to its every element. The result of that expression or function is then added to a new list.

We applied the list comprehension on my_string as:

  • Iterated every element of my_string.
  • Applied a filter to check if my_string contains the character.
  • Created a new list of elements based on the above condition.

Once we got the list, we used the len() method to store its length in the count.

Using re.findall() Method

To get a count of occurrences of a character in a string in Python:

  • Import Python library re.
  • Use re.findall() to create a new list of all matches of the character in my_string
  • Use len() to find the length of the new list.

Now we will get the following output:

Python regular expression library re is a Python module that supports compiling and executing regular expressions. It provides several functions for finding and manipulating strings using regular expressions.

The re.findall() method of the re library locates all the matches for a pattern in a string and returns a list of all those matches. We used it to locate all the matches of the character in my_string and created a new list of those matches.

On the list returned by re.findall(), we applied len() to get the count.

Using for loop with re.finditer() Method

To get the occurrence frequency of a character in a string:

  • Import Python library re.
  • Use re.finditer() to create a new list of all matches of the required character in input String.
  • Use for loop to iterate over every element of the new list.
  • Inside the for loop, increment count by 1.

The above code will print the following output on the console:

We discussed re while explaining the code using the re.findall() method.

The re.finditer() method is used to find all possible matches for a regular expression. A match object is created for each match, and each object contains a count of the character positions in the string that the pattern matched. It returns a generator object that produces match objects.

We used for loop to iterate the objects returned by re.finditer() and incremented the count on each iteration.

Use the lambda Function with map()

To get the occurrence frequency of a character in a string in Python:

    • Use the lambda function to return 1 if current character in string is equal to supplied character e.g. lambda c: 1 if character in c else 0, my_string.
  • Use the map() function to apply the lambda function to every element of my_String.
  • Use the sum() function to sum up all the occurrences returned by the map() function.

The execution of the above code will give us the following output.

A lambda function is a small anonymous function because it is undeclared with the standard def keyword.

It can take any number of arguments but can have only one expression. It is used when a function is needed for a short period.

In the lambda function, we used an expression 1 if character in c else 0 that returns 1 if the character appeared in c else 0.

The map() function in Python is a built-in function that allows you to apply a function to every item in an iterable object. It holds a function and iterables and returns an iterator object.

For example, we applied the lambda function to each element of my_String using the map() function.

Once we got an iterator object, we used the sum() function that added together all the values of the map() function and stored the sum in the count.

Use collections.Counter() Method

To count the occurrence of a character in a string:

  • Use the collections.Counter() function to create a counter object that contains the occurrence frequency of items in my_string.
  • Use count[character] to get the value of the character from the counter object.

We will get the below output on the successful execution of the above program.

The collections package in Python is a module that provides specialized container datatypes. These containers are highly optimized for performance and memory usage.

It provides classes that allow developers to create and manage complex data structures with minimal effort. From this package, we imported its Counter() class.

The collections.Counter() function creates a counter object that counts the occurrence frequency of items in a sequence.

The items are grouped by the value returned by their key function. The Counter class is a mutable subclass of dict but keeps the values in an integer key-value pair.

We applied the function on my_string to make key-value pairs of characters and their occurrence frequency. We extracted the value of the character from the counter object count using count[character].

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *