How do you count consonants in a string in python
In this exercise, you will learn how to write a Python program to count the total number of consonants present in a string. This type of logical coding question is generally asked in the programming interview. We should be aware that the perfect solution to the most fundamental coding or programming inquiries decides how we perform in an interview. There are several ways to count the total number of consonants present in a given string. Here, we have mentioned most of them-
Using forloop 1
Here is the Python program to count consonants present in a given string using a for loop. When the user entered the string as input, it passed through the for loop statement. If the letter is a consonant, the counter increases.
Output of the above code -
Enter a string: apple The number of vowels: 2 The number of consonant: 3Using forloop 2
Here is the other way to count the total consonants present in a string using a for loop. First, we initialised the consonants with a 0 variable. When the user entered the string as input, we stored it in a variable and applied the lower() method to make it case insensitive. In programming, the vowels in the uppercase string "AEIOU" count as different characters than the vowels in the lowercase string "aeiou". Next, we have passed the string through the for loop statement and checked for each character, updating the counter accordingly. If the letter is a consonant, the counter increases.
Output of the above code -
Enter a string: ostrich is the largest bird The number of consonants: 21Using Iterative Method
Here, we have used an iterative method to count total consonants in a string-
Recursive Method
Recursion function is a function that is called itself. In the given example, we have called the recursion function to get the total consonants in a string input. A recursion function continues until some condition is met to prevent it. That's why we use the if statement to break the infinite recursion.
Output of the above code -
need an explanation for this answer? contact us directly to get an explanation for this answerEnter a string: Success is journey The number of consonants: 12