Last Updated : 11 Jul, 2025
We are given a string, and our task is to count how many times a specific character appears in it using Python. This can be done using methods like .count(), loops, or collections.Counter. For example, in the string "banana", using "banana".count('a') will return 3 since the letter 'a' appears three times.
Using count()The built-in count() method in the string class makes it easy to count how many times a character appears in a string. This is ideal for counting a single character quickly and easily.
Python
s = "apple"
cnt = s.count('p')
print(cnt)
Explanation: The string "apple" contains two occurrences of character 'p'.
Using a LoopIf we want more control over the counting process then we can use a loop (for loop) to iterate through each character in the string.
Python
s = "hello world"
t = 'l'
cnt = 0
for c in s:
if c == t:
cnt += 1
print(cnt)
Explanation: This code counts how many times the character 'l' appears in the string "hello world" using a loop. It iterates through each character in the string s, and if the character matches t, it increments the counter cnt. Finally, it prints the total count.
Using collections.CounterThe Counter class from collections module is a simple and efficient way to count how many times each character appears in a string. It automatically creates a count for each character and making it easy to see how many of each character are present in the string. This is best option for efficiently counting all characters in a string with clear and concise code.
Python
from collections import Counter
s = "GeeksforGeeks"
cnt = Counter(s)
print(cnt['e'])
Explanation:
Related Articles:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4