Table of Contents
Learning how to count the occurrences of a character in string in Python can be quite useful. You can use the result to check for unwanted characters, for example. Find the best way to do so for yourself with these methods.
Count the occurrences of a character in string in Python
Using for Loops
There is no need to rely on other functions if you are willing to count characters in a string manually. This can be done with a single for loop.
The count number should be set to zero at the beginning. It will be increased by one if you encounter the character while iterating through the whole string.
Example:
sample_string = 'How To Count Occurrences of a Character in a String in Python'
count_occurrences = 0
character = input("Enter the character: ")
for a in sample_string:
if a == character:
count_occurrences = count_occurrences + 1
print("Character", character, "in the string is:",count_occurrences)
Output:
Enter the character: r
Character r in the string is: 5
Note: This method is case-sensitive.
There are two options when case-sensitivity isn’t a concern (meaning you want to find both the uppercase ‘T’ and the lowercase ‘t’).
You can try converting the original string to lowercase with the lower() method first. But comparing each character in the string to both cases is another idea. Both should yield the same result.
With lower():
sentence = 'Tom woke with a start and lifted his head.'
sentence_l = sentence.lower()
count = 0
for i in sentence_l:
if i == 't':
count = count + 1
print(count)
Output:
5
Checking for both ‘t’ and ‘T’:
sentence = 'Tom woke with a start and lifted his head.'
count = 0
for i in sentence:
if i == 't' or i == 'T':
count = count + 1
print(count)
Output:
5
Using str.count()
The string data type in Python has a built-in count() method. It returns the number of times a substring appears in a given string. This substring can be a single character as well.
Example:
sentence = 'Tom woke with a start and lifted his head.'
count = sentence.count('t')
print(count)
Output:
4
Using collections.Counter
The 2.7 version brought the collections module. It provides several container data types designed to replace general-purpose containers in Python like list, tuple, set, and dict.
Counter is such a specialized data type and offers another way to count occurrences of a character in a string in Python. Similar to multisets and bags in other programming languages, it can count hashable objects. You can take advantage of this purpose to find every instance of a character.
Example:
from collections import Counter
sentence = 'Tom woke with a start and lifted his head.'
c = Counter(sentence)
count = c['t']
print(count)
Output:
4
When the Counter object is populated with a string like the snippet above, it generates the number of appearances of every character in the string. As Counter is a subclass of dict, you can access the count for the desired character through a key like a dict.
Using Regular Expressions
Python supports regular expressions through the re module. They are sequences of characters that specify search patterns in text.
You can create a pattern matching the character and make the module’s findall() function find it for you. The length of the list it returns is the number of times the character appears in the given string.
Example:
import re
sentence = 'Tom woke with a start and lifted his head.'
count = len(re.findall("t", sentence))
print(count)
Output:
4
Using Utilize findall()
In Python, findall() can be used to count the number of times a character appears in a string. So, without wasting any time, let’s take a look at the following example:
print('I have two students'.count('t'))
import re
mystr = "I have two students"
print(len(re.findall("t", mystr)))
Output:
3
Final Words
There is no shortage of ways to count the occurrences of a character in string in Python. Depending on your purpose, you can always find a suitable option.
Hey, i have another way
If you apply lambda +
sum()
+map()
It uses
sum()
to sum up all the occurrences included applingmap()
.Then, output is
str.count(sub[, start[, end]])
Find the total figure of non-overlapping instances of the substring
sub
within this range[start and end[start, end]
.Below is an example to figure out the slices.
Simplest solution below is the explanation for counting Occurrences of a Character in a String in Python