Python Program to Count Consonants in a String

Counting consonants is another fundamental string problem in Python. It helps improve understanding of conditions, loops, and character classification.

In this tutorial, we will explore different ways to count consonants efficiently.

1. Understanding the Problem

Given a string, count how many consonants are present (all alphabets except vowels).

Input: hello world
Output: 7 (h, l, l, w, r, l, d)

2. Method 1: Using For Loop

Python
string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0

for char in string:
    if char.isalpha() and char not in vowels:
        count += 1

print("Number of consonants:", count)

This method checks if the character is an alphabet and not a vowel.

3. Method 2: Using List Comprehension

Python
string = input()
vowels = "aeiouAEIOU"

count = sum(1 for char in string if char.isalpha() and char not in vowels)
print(count)

A concise and Pythonic way to count consonants.

4. Method 3: Using Function

Python
def count_consonants(s):
    vowels = "aeiouAEIOU"
    return sum(1 for char in s if char.isalpha() and char not in vowels)

print(count_consonants("Python Programming"))

Functions improve modularity and reusability.

5. Method 4: Count Each Consonant

Python
string = input().lower()
vowels = "aeiou"
consonant_count = {}

for char in string:
    if char.isalpha() and char not in vowels:
        consonant_count[char] = consonant_count.get(char, 0) + 1

print(consonant_count)

This method tracks frequency of each consonant.

6. Method 5: Using Regular Expressions

Python
import re

string = input()
consonants = re.findall(r'[^aeiouAEIOU\W\d_]', string)
print(len(consonants))

Regex helps filter consonants efficiently.

7. Algorithm

1. Take input string.

2. Initialize count = 0.

3. Loop through each character.

4. Check if character is alphabet and not vowel.

5. Increment count.

6. Print result.

8. Common Mistakes

1. Not checking if character is alphabet.

2. Including numbers or symbols.

3. Forgetting uppercase handling.

4. Incorrect vowel exclusion logic.

9. Applications

1. Text analysis.

2. Linguistic processing.

3. Input validation systems.

4. Educational tools.

Conclusion

Counting consonants builds on vowel counting and strengthens your understanding of string manipulation in Python.

Practice different methods to write clean and optimized code.