Tuple of words containing a or e in a sentence in Python


This Python code processes the sentence and creates a tuple called ae_words. The ae_words tuple contains words from the sentence that contain at least one of the characters 'a' or 'e'. Here's how the code works:

  • sentence = "This is a sample sentence with various words.": This line initializes a variable named sentence and assigns it the given sentence.
  • ae_words = tuple(word for word in sentence.split() if 'a' in word or 'e' in word): This line initializes a variable named ae_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 after splitting it by spaces using sentence.split().
    • if 'a' in word or 'e' in word: For each word, it checks if either 'a' or 'e' is present in the word.
    • tuple(...): This surrounds the generator expression and converts the generated words that meet the condition into a tuple.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(ae_words): This line of code prints the ae_words tuple (which contains words from the sentence with 'a' or 'e') to the console.

Source Code

sentence = "This is a sample sentence with various words."
ae_words = tuple(word for word in sentence.split() if 'a' in word or 'e' in word)
print(sentence)
print(ae_words)

Output

This is a sample sentence with various words.
('a', 'sample', 'sentence', 'various')

Example Programs