Count number of Vowels and Consonants in a string using Python
In this tutorial, we will learn how to count the number of vowels and consonants in a string in python. I hope you know what consonants and vowels are. We will be using If Else statements so I hope you are familiar with them too. So now let’s get started.
Count number of Vowels and Consonants in a string in Python
First of all, We will need a string in which we will count the number of vowels and consonants. Let’s name our string my_string.
my_string="Nitesh Jhawar"
Now after the string declaration, we will create a set that will contain all the vowels with both cases (Upper and Lower).
This can be done by using an inbuilt function set() which will takes a string as an argument.
set() will convert a string into a set with values separated by a comma.
vowel = set("aeiouAEIOU") print(vowel)
Output:
{'o', 'I', 'e', 'a', 'u', 'A', 'O', 'U', 'i', 'E'}
Now we take 2 variables v_count and c_count which counts the number of vowels and consonants respectively and initialize them to zero.
v_count=0 c_count=0
We are all set to apply our logic.
Using for loop, we iterate inside my_string as,
for i in my_string:
Now we need to apply our If-Else conditions.
if i in vowel: v_count=v_count+1 elif( (i>='a' and i<='z') or (i>='A' and i<='Z')): c_count = c_count + 1
First line checks if the set vowel contains i, which was our iterating variable used in for loop. If true, the v_count will increment by one.
Else if i is between [a,z] or between [A, Z] then c_count will increment by one.
Finally, we print the value of c_count and v_count.
print(c_count) print(v_count)
Our final code looks like this:
my_string="Nitesh Jhawar" vowel = set("aeiouAEIOU") print(vowel) v_count=0 c_count=0 for i in my_string: if i in vowel: v_count=v_count+1 elif( (i>='a' and i<='z') or (i>='A' and i<='Z')): c_count = c_count + 1 print("Number of consonents in the sring:", c_count) print("Number of vowels in the string:", v_count)
Output:
{'o', 'I', 'e', 'a', 'u', 'A', 'O', 'U', 'i', 'E'} Number of consonents in the sring: 8 Number of vowels in the string: 4
Also, learn
Leave a Reply