Create a set of non-whitespace characters from a string
This Python code uses a set comprehension to create a new set named non_whitespace_chars, which contains non-whitespace characters from the string "Hello, world!". Here's how the code works:
- non_whitespace_chars = {char for char in string if not char.isspace()}: This line initializes the set non_whitespace_chars using a set comprehension.
- for char in string: This part of the code iterates through each character in the string "Hello, world!".
- if not char.isspace(): This part of the code filters the characters to include only those that are not whitespace characters. It checks if the character char is not a whitespace character using the isspace() method.
- print(string): This line of code prints the original string, "Hello, world!", to the console.
- print(non_whitespace_chars): This line of code prints the non_whitespace_chars set to the console, which contains non-whitespace characters from the string.
Source Code
string = "Hello, world!"
non_whitespace_chars = {char for char in string if not char.isspace()}
print(string)
print(non_whitespace_chars)
Output
Hello, world!
{'e', 'r', 'H', 'd', 'w', ',', 'l', '!', 'o'}