Print only Consonants in Python

Print only consonants in Python | Here, we use the for loop and list comprehension to print consonants in a string in Python. The letters ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ and ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ are called vowels letters.

In this program, we use the for loop and if-else statement to print consonants in a string. We use a user-defined function to check string contains consonants and if a string contains consonants then print.

# print only consonants in given string

def printConsonants(string):
   # printing consonants
   for c in string:
      if c not in "AEIOUaeiou ":
         print(c, end=', ')
   return c

# input from the user
string = input('String: ')

# call the function
printConsonants(string)

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

String: Know Program
K, n, w, P, r, g, r, m,

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

String: Python
[‘P’, ‘y’, ‘t’, ‘h’, ‘n’]

In this program, we are using list comprehension to print only consonants in a string.

# print only consonants in given string

def printConsonants(string):
   # printing consonants
   consonant = [c for c in string if c not in "aeiouAEIOU "]
   print(consonant)

# input from the user
string = input('String: ')

# call the function
printConsonants(string)

Output:-

String: Consonants
[‘C’, ‘n’, ‘s’, ‘n’, ‘n’, ‘t’, ‘s’]

Leave a Comment

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