Tuple of words with at least one vowel in a sentence in Python


This Python code processes the sentence and creates a tuple called vowel_words. The vowel_words tuple contains words from the sentence that contain at least one vowel. Here's how the code works:

  • sentence = "Hello, how are you?": This line initializes a variable named sentence and assigns it a string containing the input sentence.
  • vowel_words = tuple(word for word in sentence.split() if any(char.lower() in 'aeiou' for char in word)): This line initializes a variable named vowel_words and assigns it a tuple created using a generator expression.
    • for word in sentence.split(): This part of the code sets up a loop that iterates through each word word in the sentence. It does this by splitting the sentence into words using whitespace as the delimiter.
    • if any(char.lower() in 'aeiou' for char in word): For each word, it checks if there is at least one character in the word that is a vowel. It does this using the any() function with a generator expression. The generator expression checks if each character char (converted to lowercase) in the word is a vowel (i.e., it's in the string 'aeiou').
    • tuple(...): This surrounds the generator expression and converts the words that meet the condition into a tuple.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(vowel_words): This line of code prints the vowel_words tuple (which contains words with at least one vowel) to the console.

Source Code

sentence = "Hello, how are you?"
vowel_words = tuple(word for word in sentence.split() if any(char.lower() in 'aeiou' for char in word))
print(sentence)
print(vowel_words)

Output

Hello, how are you?
('Hello,', 'how', 'are', 'you?')

Example Programs