How to Count Consonants in a String in Python

Previously we had to check a character is a vowel or consonant. Now in this post, we will discuss how to count consonants in a string in python using various methods. The alphabets ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ (in uppercase) and ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ are vowels, and remaining alphabets are called consonants.

Python Program to Count Consonants in a String

This python program uses the for loop to count consonants in a string. We will take a user-defined function to count the number of consonants present in a string. Then, we will take a string while declaring the variables. Finally, call the function and the result will be displayed on the screen.

# Python program to count consonant in a string

def countConsonants(string):
   num_consonants = 0
   # to count the consonants
   for char in string:
      if char not in "aeiouAEIOU ":
         num_consonants += 1
   return num_consonants

# take input
string = input('Enter any string: ')

# calling function and display result
print('No of consonants:',countConsonants(string))

Output for the input values test-case-1:-

Enter any string: Know Program
No of consonants: 8

Output for the input values test-case-2:-

Enter any string: Python
No of consonants: 5

We can also write a program in a simple way to count consonants in a string in python.

def countConsonants(string):
   num_consonants = [each for each in string if each not in "aeiouAEIOU "]
   print('Number of consonants:', len(num_consonants))

string = input('Enter any string: ')
countConsonants(string)

Count Consonants in a String Python using While Loop

In the above program, we will count consonants in a string using the for loop but in this program, count consonants in a string using the while loop.

# Python program to count consonant in a string using while loop

def countConsonants(string):
   count = 0
   num_vowels = 0
    
   # to count the vowels
   while count < len(string):
     if string[count] == "a" or string[count] == "e" 
        or string[count] == "i" or string[count] == "o" 
          or string[count] == "u" or string[count] == "A" 
           or string[count] == "E" or string[count] == "I" 
            or string[count] == "O" or string[count] == "U":
         num_vowels = num_vowels+1
     count = count+1
    
   # to count the consonants
   num_consonants = len(string) - num_vowels
   return num_consonants

# take input
string = input('Enter any string: ')

# calling function and display result
print('Number of Consonants:', countConsonants(string))

Output:-

Enter any string: Consonants
Number of Consonants: 7

Python Program to Count the Number of Each Consonants

This python program also performs the same task but in a different way. In this method, we form a dictionary comprehension with the consonants and increment them when a consonant is encountered. This is a better and efficient way to check the number of each consonant present in a string.

# Python program to count the number of each consonants

def countConsonants(string):
   # make it suitable for caseless comparisions
   string = string.casefold()
      
   # make a dictionary with each consonants a key and value 0
   count = {i:0 for i in 'bcdfghjklmnpqrstvwxyz'}
    
   # to count the consonants
   for char in string:
      if char in count:
         count[char] += 1    
   return count

# take input
string = input('Enter any string: ')

# calling function and display result
print('Number of Consonants :', countConsonants(string))

Output:-

Enter any string: Python program to count consonants in string
Number of Consonants : {‘b’: 0, ‘c’: 2, ‘d’: 0, ‘f’: 0, ‘g’: 2, ‘h’: 1, ‘j’: 0, ‘k’: 0, ‘l’: 0, ‘m’: 1, ‘n’: 7, ‘p’: 2, ‘q’: 0, ‘r’: 3, ‘s’: 3, ‘t’: 5, ‘v’: 0, ‘w’: 0, ‘x’: 0, ‘y’: 1, ‘z’: 0}

Here, we use the casefold() method to ignore the cases. Basically, this method returns a lowercased version of the string. In each iteration, we check if the character is in the dictionary keys (True if it is a consonant) and increment the value by 1 if true.

Using a List and a Dictionary Comprehension

The above program only uses dictionary comprehension but in this program, we have nested a list comprehension inside a dictionary comprehension to count the consonants present in a string.

# Python program to count the number of each consonants

def countConsonants(string):
    # make it suitable for caseless comparisions
    string = string.casefold()
    
    # to count the consonants
    count = {x:sum([1 for char in string if char == x]) for x in 'bcdfghjklmnpqrstvwxyz'}
    print('Number of Consonants:', count)

# take input
string = input('Enter any string: ')

# calling function and display result
countConsonants(string)

Output:-

Enter any string: List Comprehension
Number of Consonants: {‘b’: 0, ‘c’: 1, ‘d’: 0, ‘f’: 0, ‘g’: 0, ‘h’: 1, ‘j’: 0, ‘k’: 0, ‘l’: 1, ‘m’: 1, ‘n’: 2, ‘p’: 1, ‘q’: 0, ‘r’: 1, ‘s’: 2, ‘t’: 1, ‘v’: 0, ‘w’: 0, ‘x’: 0, ‘y’: 0, ‘z’: 0}

In this program, the dictionary comprehension runs for all consonant characters, and the list comprehension checks inside the dictionary comprehension if any characters in a string match that particular consonant. Finally, The sum() method calculates the sum of the elements.

Leave a Comment

Your email address will not be published.