Print only Consonants in Python

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

Print consonants in a String in Python

In this program, we are using the for loop to print consonants in a string. We will take a user-defined function to check and print if a string contains 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 consonants in a string

def printConsonants(string):
   # to print the consonants
   for char in string:
      if char not in "aeiouAEIOU ":
         print(char, end=', ')
   return char

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

# calling function
printConsonants(string)

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

Enter any string: Know Program
K, n, w, P, r, g, r, m,

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

Enter any string: Python
[‘P’, ‘y’, ‘t’, ‘h’, ‘n’]

Print only Consonants 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 consonants in a string.

# Python program to print consonants in a string

def printConsonants(string):
   # to print the consonants
   consonants = [each for each in string if each not in "aeiouAEIOU "]
   print(consonants)

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

# calling function
printConsonants(string)

Output:-

Enter any string: Consonants
[‘C’, ‘n’, ‘s’, ‘n’, ‘n’, ‘t’, ‘s’]

Leave a Comment

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