Count the Occurrence of a Character in a String in Python

  1. Use count() to Count Character Occurrence in Python
  2. Use regex Function findAll() to Count Occurrence in Python String

This tutorial will demonstrate how to count the occurrence of a character in a string in Python. It will also cover other possibilities: a set of characters, a substring, and regular expressions.

Use count() to Count Character Occurrence in Python

Python has a built-in string function called count() that accepts a substring parameter and counts the number of times it appears in the string.

Let’s declare a sample string with a few repeated characters and test the function.

sentence = 'Cats, rats, bats, and hats.'

print('occurrence of letter a:', sentence.count('a'))

Output:

occurrence of letter a: 5

Passing a substring with more than one character is also supported by the count() function.

print('occurrence of substring ats:', sentence.count('ats'))

Output:

occurrence of substring ats: 4

Use regex Function findAll() to Count Occurrence in Python String

Suppose the substring you want to match is less specific but follows a pattern. In that case, we can make use of the Python regular expression module re and its findAll() function to match specific patterns supported by regular expressions.

Below is the example to count occurrences of a in the string using the regex method.

import re
sentence = 'Cats, rats, bats, and hats.'

print('occurrence of letter a:', len(re.findall('a', sentence)))

Output:

occurrence of letter a: 5

For example, to search for all occurrences of vowels in a string, we can use findAll() with the regEx pattern for vowels. It will return a list of all the matches within the string. Then, wrap the result around the function len() to print out how many matches it makes.

import re

sentence = 'The quick brown fox jumps over the lazy dog'
vowels = re.findall('[aeiou]', sentence)

print("occurrences of vowels:", len())
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Remove Quotes From String in Python
  • Check if Input Is Integer in Python
  • Related Article - Python Character

  • Convert a String to Binary in Python