Skip to content

Python count specific characters in string

  • by

To counts specific characters in string use Counter from 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 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)


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

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

Your email address will not be published. Required fields are marked *