Tuple of distinct consonants in a sentence in Python


This Python code creates a tuple called consonants, which contains all the lowercase consonant characters from the sentence string. Here's how the code works:

  • sentence = "Hello, how are you?": This line initializes a variable named sentence and assigns it the string "Hello, how are you?"
  • consonants = tuple(char.lower() for char in sentence if char.lower() not in 'aeiou' and char.isalpha()): This line of code initializes a variable named consonants and assigns it a tuple created using a generator expression.
    • for char in sentence: This part of the code sets up a loop that iterates through each character char in the sentence.
    • if char.lower() not in 'aeiou': For each character in the string, it checks if the lowercase version of char is not in the string 'aeiou', effectively identifying consonants.
    • and char.isalpha(): It also checks if the character is an alphabet letter (i.e., not a punctuation mark or space) using the char.isalpha() method.
    • char.lower(): If the character meets both conditions (is a consonant and is an alphabet letter), it converts char to lowercase using char.lower() and includes it in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated lowercase consonants into a tuple.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(consonants): This line of code prints the consonants tuple (which contains the lowercase consonant characters from the sentence) to the console.

Source Code

sentence = "Hello, how are you?"
consonants = tuple(char.lower() for char in sentence if char.lower() not in 'aeiou' and char.isalpha())
print(sentence)
print(consonants)

Output

Hello, how are you?
('h', 'l', 'l', 'h', 'w', 'r', 'y')

Example Programs