Count the Number of Consonants in a String in Python
Counting consonants in a string is a common programming task, often paired with counting vowels. Consonants are all alphabetic characters that are not vowels (A, E, I, O, U). In this tutorial, we’ll explore different methods to count the consonants in a string using Python, from simple loops to more advanced techniques.
What Are Consonants?
In English, consonants are letters in the alphabet that are not vowels: A, E, I, O, U. This means all other letters, like B, C, D, F, G, H, etc., are consonants. For our purposes, we’ll also ignore any non-alphabetic characters.
Method 1: Using a for
Loop and Conditional Statements
One straightforward way to count consonants in a string is by looping through each character and checking if it’s a consonant.
Code Example:
# Program to count the number of consonants in a string using a loop
# Step 1: Define a function to count consonants
def count_consonants(s):
count = 0
vowels = "aeiouAEIOU" # List of vowels (both lowercase and uppercase)
for char in s:
# Step 2: Check if the character is a consonant
if char.isalpha() and char not in vowels:
count += 1
return count
# Step 3: Test the function
string = "Hello, World!"
consonant_count = count_consonants(string)
print(f"The number of consonants in '{string}' is: {consonant_count}")
Explanation:
- Loop through Characters: We iterate through each character in the string.
- Condition Check: We check if the character is an alphabetic letter and is not a vowel.
- Count Increment: If both conditions are true, we increment the count.
Output:
The number of consonants in 'Hello, World!' is: 7
Method 2: Using List Comprehension
List comprehension provides a compact way to count consonants in a single line of code.
Code Example:
# Program to count the number of consonants in a string using list comprehension
# Step 1: Define a function to count consonants
def count_consonants(s):
# Use list comprehension to count consonants
return sum(1 for char in s if char.isalpha() and char not in "aeiouAEIOU")
# Step 2: Test the function
string = "Python Programming"
consonant_count = count_consonants(string)
print(f"The number of consonants in '{string}' is: {consonant_count}")
Explanation:
- List Comprehension: For each character that’s an alphabetic consonant, we add
1
. - Sum Function:
sum()
adds all1
s, giving the total count of consonants.
Output:
The number of consonants in 'Python Programming' is: 12
Method 3: Using Regular Expressions
Using Python’s re
module allows you to count consonants using regular expressions.
Code Example:
# Program to count the number of consonants in a string using regular expressions
import re
# Step 1: Define a function to count consonants
def count_consonants(s):
# Use regex to find all consonants (case-insensitive)
return len(re.findall(r'(?i)[bcdfghjklmnpqrstvwxyz]', s))
# Step 2: Test the function
string = "Data Science"
consonant_count = count_consonants(string)
print(f"The number of consonants in '{string}' is: {consonant_count}")
Explanation:
- Regex Pattern: The pattern
[bcdfghjklmnpqrstvwxyz]
matches consonants, and(?i)
makes it case-insensitive. - findall():
findall()
returns a list of all consonant matches. - len():
len()
counts the consonants in the list.
Output:
The number of consonants in 'Data Science' is: 7
Method 4: Using Counter
from collections
With Counter
from Python’s collections
module, counting consonants is efficient and concise.
Code Example:
# Program to count the number of consonants in a string using Counter
from collections import Counter
# Step 1: Define a function to count consonants
def count_consonants(s):
counter = Counter(s) # Count each character in the string
vowels = "aeiouAEIOU"
# Step 2: Sum counts for all alphabetic characters that are not vowels
return sum(counter[char] for char in counter if char.isalpha() and char not in vowels)
# Step 3: Test the function
string = "Machine Learning"
consonant_count = count_consonants(string)
print(f"The number of consonants in '{string}' is: {consonant_count}")
Explanation:
- Counter:
Counter(s)
counts occurrences of each character. - Sum Consonant Counts: We iterate through each character, adding up counts for alphabetic characters that are not vowels.
Output:
The number of consonants in 'Machine Learning' is: 9
Method 5: Using Lambda and filter()
You can also count consonants using filter()
combined with a lambda function for a functional programming approach.
Code Example:
# Program to count the number of consonants in a string using lambda and filter
# Step 1: Define a function to count consonants
def count_consonants(s):
vowels = "aeiouAEIOU"
return len(list(filter(lambda char: char.isalpha() and char not in vowels, s)))
# Step 2: Test the function
string = "Artificial Intelligence"
consonant_count = count_consonants(string)
print(f"The number of consonants in '{string}' is: {consonant_count}")
Explanation:
- Lambda and Filter:
filter()
applies the lambda function to each character, keeping only consonants. - List and
len()
: We convert the result to a list and uselen()
to get the count.
Output:
The number of consonants in 'Artificial Intelligence' is: 14
Conclusion
In this blog, we explored various ways to count consonants in a string in Python:
- Loop and Condition: Checks each character for consonants.
- List Comprehension: Concise one-liner approach.
- Regular Expressions: Efficiently finds consonants with pattern matching.
- Counter from
collections
: Quick character counting. - Lambda with
filter()
: Functional approach using filtering.
Choose the method that best suits your needs and coding style. Happy coding! 😊
Stay tuned for more Python programming tutorials and tips!