Create a set of vowels from a string


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

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

Source Code

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

Output

Hello, world!
{'e', 'o'}

Example Programs