How to Separate Vowels and Consonants in a String in Python | Previously, we had to check a character is a vowel or consonant. Here, we will discuss how to separate vowels and consonants in a string in Python.
Python Program to Separate Vowels and Consonants in a String
In this program, we are using for loop and if-else statements to separate vowels and consonants in a string.
# Python program to separate vowels and consonants in a string
string = input('String: ')
print('Vowels: ')
for ch in string:
if ch in "AEIOUaeiou":
print(ch, end=', ')
print('\nConsonants: ')
for ch in string:
if ch not in "AEIOUaeiou ":
print(ch, end=', ')
Output for the input values test-case-1:-
String: Know Program
Vowels:
o, o, a,
Consonants:
K, n, w, P, r, g, r, m,
Output for the input values test-case-2:-
String: separate
Vowels:
e, a, a, e,
Consonants:
s, p, r, t,
How to Separate Vowels and Consonants in a String in Python
We use list comprehension methods to print the vowels and the consonants in the string.
# 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)
# inputs and call function
string = input('String: ')
vowelsConsonants(string)
Output:-
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’]