Open In App

Count Occurrences of a Character in String in Python

Last Updated : 09 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Output
2

Explanation: The string "apple" contains two occurrences of character 'p'.

Using a Loop

If 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)

Output
3

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.Counter

The 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'])

Output
4

Explanation:

  • Counter(s) counts how many times each character appears in the string.
  • To find out how many times the character 'e' appears, just use count['e'], which gives us 4.

Related Articles:


Practice Tags :

Similar Reads