Table of Contents
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.
|
1 2 3 4 5 6 |
my_string = "This code snippet counts occurrences of a character in a string in python" character = 'c' count = my_string.count(character) print(f'Occurrences of character \'{character}\': {count}') |
We will get the following result after running the above program.
|
1 2 3 |
Occurrences of character 'c': 7 |
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
forloop to iterate over each character of input String. - For each character, use the
ifstatement to check if suppliedcharacterappears in String. - Increment the
countby1if character exists in String.
|
1 2 3 4 5 6 7 8 9 10 11 |
my_string = "This code snippet counts occurrences of a character in a string in python" character = 'c' count = 0 for element in my_string: if element == character: count+=1 print(f'Occurrences of character \'{character}\': {count}') |
We will get the below output on the successful execution of the above program.
|
1 2 3 |
Occurrences of character 'c': 7 |
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
forloop to iterate everycharacterof input string. - Append the
elementto a new list if the requiredcharacterappears in string. - Use the
len()method to find the occurrence of thecharacterin string.
|
1 2 3 4 5 6 7 8 9 10 11 |
my_string = "This code snippet counts occurrences of a character in a string in python" character = 'c' count = len([ element for element in my_string if element == character ]) print(f'Occurrences of character \'{character}\': {count}') |
The code above will print the following output on the console:
|
1 2 3 |
Occurrences of character 'c': 7 |
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
elementofmy_string. - Applied a filter to check if
my_stringcontains thecharacter. - 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 thecharacterinmy_string - Use
len()to find the length of the new list.
|
1 2 3 4 5 6 7 |
import re my_string = "This code snippet counts occurrences of a character in a string in python" character = 'c' count = len(re.findall(character, my_string)) print(f'Occurrences of character \'{character}\': {count}') |
Now we will get the following output:
|
1 2 3 |
Occurrences of character 'c': 7 |
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 requiredcharacterin input String. - Use
forloop to iterate over everyelementof the new list. - Inside the
forloop, incrementcountby1.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import re my_string = "This code snippet counts occurrences of a character in a string in python" character = 'c' count = 0 for element in re.finditer(character, my_string): count += 1 print(f'Occurrences of character \'{character}\': {count}') |
The above code will print the following output on the console:
|
1 2 3 |
Occurrences of character 'c': 7 |
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.
Further reading:
Use the lambda Function with map()
To get the occurrence frequency of a character in a string in Python:
-
- Use the
lambdafunction 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
- Use the
map()function to apply thelambdafunction to every element ofmy_String. - Use the
sum()function to sum up all the occurrences returned by themap()function.
|
1 2 3 4 5 6 7 |
my_string = "This code snippet counts occurrences of a character in a string in python" character = 'c' count = sum(map(lambda c: 1 if character in c else 0, my_string)) print(f'Occurrences of character \'{character}\': {count}') |
The execution of the above code will give us the following output.
|
1 2 3 |
Occurrences of character 'c': 7 |
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 inmy_string. - Use
count[character]to get the value of thecharacterfrom the counter object.
|
1 2 3 4 5 6 7 8 |
from collections import Counter my_string = "This code snippet counts occurrences of a character in a string in python" character = 'c' count = Counter(my_string) print(f'Occurrences of character \'{character}\': {count[character]}') |
We will get the below output on the successful execution of the above program.
|
1 2 3 |
Occurrences of character 'c': 7 |
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].