Create a set of uppercase words from a sentence
This Python code uses a set comprehension to create a set named uppercase_words that contains the uppercase versions of the words in the input sentence. Here's how the code works:
- sentence = "This is a sample sentence.": This line initializes a string named sentence containing a sample sentence.
- uppercase_words = {word.upper() for word in sentence.split()}: This line initializes the set uppercase_words using a set comprehension.
- for word in sentence.split(): This part of the code splits the sentence into words using the split() method and sets up a loop to iterate through the words.
- {word.upper()}: For each word, this part includes its uppercase version (converted using the upper() method) in the uppercase_words set.
- print(sentence): This line of code prints the original sentence to the console.
- print(uppercase_words): This line of code prints the uppercase_words set to the console.
Source Code
sentence = "This is a sample sentence."
uppercase_words = {word.upper() for word in sentence.split()}
print(sentence)
print(uppercase_words)
Output
This is a sample sentence.
{'SAMPLE', 'THIS', 'SENTENCE.', 'A', 'IS'}