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.
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)
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.
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)
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)
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.
sentence = 'Tom woke with a start and lifted his head.' count = sentence.count('t') print(count)
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.
from collections import Counter sentence = 'Tom woke with a start and lifted his head.' c = Counter(sentence) count = c['t'] print(count)
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.
import re sentence = 'Tom woke with a start and lifted his head.' count = len(re.findall("t", sentence)) print(count)
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)))
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()to sum up all the occurrences included appling
Then, output is
str.count(sub[, start[, end]])
Find the total figure of non-overlapping instances of the substring
subwithin 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