Tuple of ASCII values for characters in a string in Python
This Python code creates a tuple called ascii_values, which contains the ASCII values (ordinal values) of each character in the string string. Here's how the code works:
- string = "hello": This line initializes a variable named string and assigns it the string "hello."
- ascii_values = tuple(ord(char) for char in string): This line of code initializes a variable named ascii_values and assigns it a tuple created using a generator expression.
- for char in string: This part of the code sets up a loop that iterates through each character char in the string.
- ord(char): For each character in the string, it uses the ord() function to get its ASCII value (ordinal value).
- tuple(...): This surrounds the generator expression and converts the generated ASCII values into a tuple.
- print(string): This line of code prints the original string to the console.
- print(ascii_values): This line of code prints the ascii_values tuple (which contains the ASCII values of the characters in the string) to the console.
Source Code
string = "hello"
ascii_values = tuple(ord(char) for char in string)
print(string)
print(ascii_values)
Output
hello
(104, 101, 108, 108, 111)