Count Consonants in String
In this lesson, you will learn how to count consonants of a string using both an iterative and recursive approach in Python.
We'll cover the following...
In this lesson, we focus on the following problem:
Given a string, calculate the number of consonants present.
The vowels are the following letters:
a e i o u
Any other letter that is not a vowel is a consonant.
Let’s have a look at an example:
Welcome to Educative!
has 9
consonants.
Before you dive into the implementation, consider the edge cases such as spaces and exclamation marks. This implies that if a character is not a vowel, it has to be a letter to be considered a consonant.
Iterative Approach
Check out the iterative approach in the snippet below:
vowels = "aeiou"def iterative_count_consonants(input_str):consonant_count = 0for i in range(len(input_str)):if input_str[i].lower() not in vowels and input_str[i].isalpha():consonant_count += 1return consonant_count
On line 1, we define vowels
globally to be "aeiou"
. input_str
is the given string passed to iterative_count_consonants
function which we have to process to calculate the number of consonants. consonant_count
is initialized to 0
on line 4 and then the input_str
is traversed character by character using a for
loop on ...