Create a set of characters that are consonants from a string


This Python code uses a set comprehension to create a set named consonants that contains all the consonant characters from the input string. Here's how the code works:

  • string = "Hello, world!": This line initializes a string named string containing letters, spaces, and punctuation.
  • consonants = {char for char in string if char.isalpha() and char.lower() not in 'aeiou'}: This line initializes the set consonants using a set comprehension.
    • for char in string: This part of the code sets up a loop that iterates through each character in the string.
    • {char.isalpha() and char.lower() not in 'aeiou'}: For each character, this part includes the character in the consonants set if it is an alphabetical character (i.e., char.isalpha()) and not a lowercase vowel (i.e., char.lower() not in 'aeiou').
  • print(string): This line of code prints the original string to the console.
  • print(consonants): This line of code prints the consonants set to the console.

Source Code

string = "Hello, world!"
consonants = {char for char in string if char.isalpha() and char.lower() not in 'aeiou'}
print(string)
print(consonants)

Output

Hello, world!
{'H', 'r', 'w', 'd', 'l'}

Example Programs