How to Separate Vowels and Consonants in a String in Python

Previously we had to check a character is a vowel or consonant. Now in this post, we will discuss how to separate vowels and consonants in a string in Python. 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 Separate Vowels and Consonants in a String

In this program, we are using the for loop to separate vowels and consonants in a string. We will take a string while declaring the variables. Then, print separate vowels and consonants.

# Python program to separate vowels and consonants in a string

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

print('Vowels: ')
for char in string:
   if char in "aeiouAEIOU":
      print(char, end=', ')

print('\nConsonants: ')
for char in string:
   if char not in "aeiouAEIOU ":
      print(char, end=', ')

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

Enter any string: Know Program
Vowels:
o, o, a,
Consonants:
K, n, w, P, r, g, r, m,

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

Enter any string: separate
Vowels:
e, a, a, e,
Consonants:
s, p, r, t,

How to Separate 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 to print vowels and consonants in string. We can also take the help of a function. A function is a block of code that performs a specific task.

# Python program to separate 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:-

Enter any string: Vowels Consonants
Number of vowels: 5 [‘o’, ‘e’, ‘o’, ‘o’, ‘a’]
Number of consonants: 11 [‘V’, ‘w’, ‘l’, ‘s’, ‘C’, ‘n’, ‘s’, ‘n’, ‘n’, ‘t’, ‘s’]

Leave a Comment

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