Python Program to Print Vowels and Consonants in a String

Previously we had to check a character is a vowel or consonant. Now in this post, we will discuss the Python program to print vowels and consonants in string. The alphabets ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ (in uppercase) and ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ are vowels, and remaining alphabets are called consonants.

Python Program to Print Vowels and Consonants in a String

In this program, we are using the if-else statements to print vowels and consonants in a string. We will take a user-defined function to print vowels and consonants. Then, we will take a string while declaring the variables. Finally, call the function and the result will be displayed on the screen.

# Python program to print vowels and consonants in a string

def vowelConsonant(string):
   #check alphabet or not
   if not string.isalpha():
      return 'Neither'
   #check vowel or consonant
   if string.lower() in 'aeiou':
      return 'Vowel'
   else:
      return 'Consonant'

# take input
string = input('Enter any string: ')

# calling function and display result
for ch in string:
   #print vowels and consonants
   print(ch,'is',vowelConsonant(ch),end=', ')

Output for the input values test-case-1:-

Enter any string: Know Program
K is Consonant, n is Consonant, o is Vowel, w is Consonant, is Neither, P is Consonant, r is Consonant, o is Vowel, g is Consonant, r is Consonant, a is Vowel, m is Consonant,

Output for the input values test-case-2:-

Enter any string: Python
P is Consonant, y is Consonant, t is Consonant, h is Consonant, o is Vowel, n is Consonant,

How to Print Vowels and Consonants in a String in Python

This python program also performs the same task but in a different way. In this program, we are using list comprehension and for loop to print vowels and consonants in string.

# Python program to print vowels and consonants in a string

def vowelsConsonants(string):
   # to count and print the vowels
   vowels = [each for each in string if each in "aeiouAEIOU"]
   print('Number of vowels:', len(vowels), vowels)
    
   # to count and print the consonants
   consonants = [each for each in string if each not in "aeiouAEIOU "]
   print('Number of consonants:', len(consonants), consonants)

# take input
string = input('Enter any string: ')

# calling function
vowelsConsonants(string)

Output for the input values test-case-1:-

Enter any string: Know Program
Number of vowels: 3 [‘o’, ‘o’, ‘a’]
Number of consonants: 8 [‘K’, ‘n’, ‘w’, ‘P’, ‘r’, ‘g’, ‘r’, ‘m’]

Output for the input values test-case-2:-

Enter any string: Python
Number of vowels: 1 [‘o’]
Number of consonants: 5 [‘P’, ‘y’, ‘t’, ‘h’, ‘n’]

Leave a Comment

Your email address will not be published. Required fields are marked *