Create a set of strings with characters in uppercase
This Python code uses a set comprehension to create a new set named uppercase_strings that contains the uppercase versions of the words in the input set strings. Here's how the code works:
- strings = {"apple", "banana", "cherry"}: This line initializes a set named strings with three string elements.
- uppercase_strings = {word.upper() for word in strings}: This line initializes the set uppercase_strings using a set comprehension.
- for word in strings: This part of the code sets up a loop that iterates through each word (string) in the strings set.
- {word.upper()}: For each word, this part includes the uppercase version of the word in the uppercase_strings set using the .upper() method.
- print(strings): This line of code prints the original set strings to the console.
- print(uppercase_strings): This line of code prints the uppercase_strings set to the console.
Source Code
strings = {"apple", "banana", "cherry"}
uppercase_strings = {word.upper() for word in strings}
print(strings)
print(uppercase_strings)
Output
{'banana', 'apple', 'cherry'}
{'APPLE', 'BANANA', 'CHERRY'}