ASCII conversion
ASCII (American Standard Code for Information Interchange) is a code used for storing letters, numbers and symbols.
|
32 |
… | 65 | 66 | … | 97 | 98 |
| Space | … | A | B | … | a |
b |
Python can convert characters into ASCII values and vice-versa.
ord() and chr()
- ord() changes a character into its Unicode number.
- chr() changes a Unicode number back into its character.
They are opposites of each other and often used together.
Examples
letter = "A"
num = ord(letter) # changes "A" to 65
print("Number:", num)
back = chr(num) # changes 65 back to "A"
print("Character:", back)
# Display ASCII value of each character
word = "Cat"
for i in range(len(word)):
char = word[i]
ascii_val = ord(char)
print(ascii_val)
# Display ASCII value of each character in array
names = ["Bob", "Anna", "Chris"]
for i in range(len(names)):
for j in range(len(names[i])):
char = names[i][j]
ascii_val = ord(char)
print(ascii_val)