Generate a set of ASCII values of characters from a string


This Python code uses a set comprehension to create a set named ascii_values that contains the ASCII values of the characters in the input string. Here's how the code works:

  • string = "Hello, world!": This line initializes a string named string containing the text "Hello, world!".
  • ascii_values = {ord(char) for char in string}: This line initializes the set ascii_values 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.
    • {ord(char)}: For each character, this part includes its ASCII value, calculated using the ord() function, in the ascii_values set.
  • print(string): This line of code prints the original string to the console.
  • print(ascii_values): This line of code prints the ascii_values set to the console.

Source Code

string = "Hello, world!"
ascii_values = {ord(char) for char in string}
print(string)
print(ascii_values)

Output

Hello, world!
{32, 33, 100, 101, 72, 108, 44, 111, 114, 119}

Example Programs