Python ProgrammingPython Programming

Different ways to count the number of occurrences of a character in a string

import re
from collections import Counter
 
sentence = 'Canada is located in the northern part of North America'
# Example I
counter = len(re.findall("a", sentence))
print(counter)
 
# Example II
counter = sentence.count('a')
print(counter)
 
# Example III
counter = Counter(sentence)
print(counter['a'])
Sample output of above program.

6
6
6