Create a list of strings with vowels replaced by asterisks


This Python code takes a list of strings and creates a new list called vowel_replaced using a list comprehension. The new list contains the same words as the original list, but with vowels replaced by asterisks ('*'). Here's how the code works:

  • strings = ["apple", "banana", "cherry"]: This line initializes a variable named strings and assigns it a list containing three words.
  • vowel_replaced = [''.join(['*' if char.lower() in 'aeiou' else char for char in word]) for word in strings]: This line of code initializes a variable named vowel_replaced and assigns it the result of a nested list comprehension.
    • for word in strings: This part sets up an outer loop that iterates through each word word in the strings list.
    • [ '*' if char.lower() in 'aeiou' else char for char in word] : For each word in the list, this inner list comprehension sets up an inner loop that iterates through each character char in the word
      • ' *' if char.lower() in 'aeiou' else char: For each character in the word, this expression checks if char (converted to lowercase) is a vowel (i.e., it checks if it's in the string 'aeiou'). If char is a vowel, it replaces it with an asterisk ('*'), otherwise, it keeps the character as is.
    • ''.join(['*' if char.lower() in 'aeiou' else char for char in word]): This expression joins the characters in the inner list (either vowels replaced with '*', or the original characters) back together to form a new word.
    • [''.join(['*' if char.lower() in 'aeiou' else char for char in word]) for word in strings]: This is the outer list comprehension itself. It iterates through the words in the strings list, processes each word by replacing vowels with asterisks, and includes the processed words in the new list.
  • print(strings): This line of code prints the original strings list to the console.
  • print(vowel_replaced): This line of code prints the vowel_replaced list to the console.

Source Code

strings = ["apple", "banana", "cherry"]
vowel_replaced = [''.join(['*' if char.lower() in 'aeiou' else char for char in word]) for word in strings]
print(strings)
print(vowel_replaced)

Output

['apple', 'banana', 'cherry']
['*ppl*', 'b*n*n*', 'ch*rry']

Example Programs