Python - How To Count the Occurrence of a Character in a String in Python

ID : 118

viewed : 79

Tags : PythonPython StringPython Character

vote vote


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


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


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 .

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


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

  • Related HOW TO?