Generate a set of characters that are not alphanumeric from a string


This Python code uses a set comprehension to create a set named non_alphanumeric that contains all the non-alphanumeric characters from the input string. Here's how the code works:

  • string = "Hello, world!": This line initializes a string named string containing letters, spaces, and punctuation.
  • non_alphanumeric = {char for char in string if not char.isalnum()}: This line initializes the set non_alphanumeric using a set comprehension.
    • for char in string: This part of the code sets up a loop that iterates through each character in the string.
    • {char.isalnum()}: For each character, this part includes the character in the non_alphanumeric set if it is not alphanumeric. The condition char.isalnum() checks whether the character is alphanumeric or not.
  • print(string): This line of code prints the original string to the console.
  • print(non_alphanumeric): This line of code prints the non_alphanumeric set to the console.

Source Code

string = "Hello, world!"
non_alphanumeric = {char for char in string if not char.isalnum()}
print(string)
print(non_alphanumeric)

Output

Hello, world!
{'!', ' ', ','}

Example Programs