Skip to content

Python count specific characters in string

  • by

To count specific characters in a string use Counter from the collections module and then just iterate over the counter, if the char is found, add its count to the res.

Python counts specific characters in a string

Simple example code.

from collections import Counter

s = "count specific characters in a string"

counts = Counter(s)

res = 0
for letter in counts:
    if letter in ['c']:
        res += counts[letter]

print("c count:", res)

Output:

Python counts specific characters in string

For example to get the total count of (A, a)’s you would do:

print('Count of A\'s is: {}'.format(counts['A'] + counts['a']))

Here’s a complete example demonstrating these methods:

string = "hello world"
char = 'l'

# Method 1: Using the count() method
count1 = string.count(char)
print(f"[count() method] The character '{char}' appears {count1} times in the string.")

# Method 2: Using a loop
count2 = 0
for c in string:
    if c == char:
        count2 += 1
print(f"[Loop] The character '{char}' appears {count2} times in the string.")

# Method 3: Using collections.Counter
from collections import Counter
counter = Counter(string)
count3 = counter[char]
print(f"[collections.Counter] The character '{char}' appears {count3} times in the string.")

# Method 4: Using a dictionary comprehension
count_dict = {c: string.count(c) for c in set(string)}
count4 = count_dict[char]
print(f"[Dictionary Comprehension] The character '{char}' appears {count4} times in the string.")

These methods provide flexibility depending on your specific needs and the complexity of your counting tasks.

Do comment if you have any doubts or suggestions on this Python count topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading