How to detect vowels vs consonants in Python?


In the English alphabet, vowels are the letters a, e, i, o, and u. Examples of words that contain vowels include "apple", "elephant", "igloo", "octopus", and "umbrella".

Consonants are all the other letters in the English alphabet, which include b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, and z. Examples of words that contain consonants include "ball", "cat", "dog", "fish", "green", and "hat".

Here are some code examples with step-by-step explanations to detect vowels and consonants in Python:

Using a for loop and conditional statements

Example

Define the string to check for vowels and consonants.

Initialize the counters for vowels and consonants to 0.

Loop through each character in the string.

Check if the lowercase version of the character is in the string "aeiou". If so, increment the vowel counter.

If the character is alphabetical but not a vowel, increment the consonant counter.

Print the results of the counters.

string = "lorem ipsum"
vowels = 0
consonants = 0
for char in string:
    if char.lower() in "aeiou":
        vowels += 1
    elif char.isalpha():
        consonants += 1
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

Output

Number of vowels: 4
Number of consonants: 6

Using list comprehension and sets

Example

Define the string to check for vowels and consonants.

Use a list comprehension to create a list of all the characters in the string that are lowercase vowels.

Use the built-in len() function to get the number of items in the list, which is the number of vowels.

Use another list comprehension to create a list of all the alphabetical characters in the string that are not lowercase vowels.

Use the built-in len() function to get the number of items in the list, which is the number of consonants.

Print the results of the counters.

string = "lorem ipsum"
vowels = len([char for char in string if char.lower() in {'a', 'e', 'i', 'o', 'u'}])
consonants = len([char for char in string if char.isalpha() and char.lower() not in {'a', 'e', 'i', 'o', 'u'}])
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

Output

Number of vowels: 4
Number of consonants: 6

Using regular expressions

Example

Import the built-in re module, which provides support for regular expressions.

Define the string to check for vowels and consonants.

Use the re.findall() function to find all matches of the regular expression pattern "[aeiou]", which matches any lowercase vowel, ignoring case.

Use the built-in len() function to get the number of matches, which is the number of vowels.

Use re.findall() again with the regular expression pattern "[b-df-hj-np-tv-z]", which matches any lowercase consonant, ignoring case.

Use len() again to get the number of matches, which is the number of consonants.

Print the results of the counters.

import re
string = "lorem ipsum"
vowels = len(re.findall("[aeiou]", string, re.IGNORECASE))
consonants = len(re.findall("[b-df-hj-np-tv-z]", string, re.IGNORECASE))

print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

Output

Number of vowels: 4
Number of consonants: 6

Using sets and intersection

Example

Define the string to check for vowels and consonants.

Use the set() function to create a set of all the characters in the string, converted to lowercase.

Use the set.intersection() method to find the intersection between this set and the set of lowercase vowels, and use the len() function to get the number of elements in the resulting set.

Repeat step 3, but with the set of lowercase consonants instead.

Print the results of the counters. Here repeated characters are counted as one.

string = "lorem ipsum"
vowels = len(set(string.lower()).intersection({'a', 'e', 'i', 'o', 'u'}))
consonants = len(set(string.lower()).intersection(set('bcdfghjklmnpqrstvwxyz')))
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

Output

Number of vowels: 4
Number of consonants: 5

Using dictionary and string formatting

Example

Define the string to check for vowels and consonants.

Create a dictionary with keys for 'vowels' and 'consonants', and set their initial values to 0.

Loop through each character in the string.

If the lowercase version of the character is in the string "aeiou", increment the 'vowels' value in the dictionary.

If the character is alphabetical but not a vowel, increment the 'consonants' value in the dictionary.

Use string formatting to print the results of the counters in the dictionary.

string = "lorem ipsum"

count = {'vowels': 0, 'consonants': 0}
for char in string:
    if char.lower() in 'aeiou':
        count['vowels'] += 1
    elif char.isalpha():
        count['consonants'] += 1
print("Number of vowels: {vowels}\nNumber of consonants: {consonants}".format(**count))

Output

Number of vowels: 4 Number of consonants: 6

Using Counter and filter

Example

Import the Counter class from the collections module.

Define the string to check for vowels and consonants.

Use the filter() function to create a new iterator with only the characters that are lowercase vowels, and use the Counter() constructor to count the occurrences of each vowel.

Sum the counts for each vowel to get the total number of vowels.

Repeat steps 3-4, but filter for alphabetical characters that are not vowels and use the sum() function to get the total count of consonants.

Print the results of the counters.

from collections import Counter
string = "lorem ipsum"
count = Counter(filter(lambda c: c.lower() in 'aeiou', string))
vowels = count['a'] + count['e'] + count['i'] + count['o'] + count['u']
count = Counter(filter(lambda c: c.isalpha() and c.lower() not in 'aeiou', string))
consonants = sum(count.values())
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

Output

Number of vowels: 4
Number of consonants: 6

Updated on: 10-Aug-2023

928 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements