Create a set of words with their vowels replaced by underscores


This Python code uses a set comprehension to create a new set named vowel_replaced, which contains words from the input set words with vowels replaced by underscores. Here's how the code works:

  • words = {"apple", "banana", "cherry"}: This line initializes a set named words with three string elements.
  • vowel_replaced = {''.join(['_' if char.lower() in 'aeiou' else char for char in word]) for word in words}: This line initializes the set vowel_replaced using a set comprehension.
    • for word in words: This part of the code sets up a loop that iterates through each word (string) in the words set.
    • ''.join(['_' if char.lower() in 'aeiou' else char for char in word]): For each word, this part creates a new string where each character is replaced by an underscore ('_') if it's a vowel (in lowercase), or left unchanged if it's not a vowel.
  • print(words): This line of code prints the original set words to the console.
  • print(vowel_replaced): This line of code prints the vowel_replaced set to the console.

Source Code

words = {"apple", "banana", "cherry"}
vowel_replaced = {''.join(['_' if char.lower() in 'aeiou' else char for char in word]) for word in words}
print(words)
print(vowel_replaced)

Output

{'banana', 'cherry', 'apple'}
{'_ppl_', 'ch_rry', 'b_n_n_'}

Example Programs