Generate a set of non-vowel characters from a string


This Python code uses a set comprehension to create a set named non_vowels that contains the non-vowel characters in the input string. Here's how the code works:

  • string = "Hello, world!": This line initializes a string named string containing the text "Hello, world!".
  • non_vowels = {char for char in string if char.lower() not in 'aeiou'}: This line initializes the set non_vowels 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}: For each character, this part includes it in the non_vowels set if it is not a vowel. The condition char.lower() not in 'aeiou' checks if the lowercase version of the character is not in the string 'aeiou', effectively filtering out vowels.
  • print(string): This line of code prints the original string to the console.
  • print(non_vowels): This line of code prints the non_vowels set to the console.

Source Code

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

Output

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

Example Programs