ASCII to character

In Python, the chr() function takes a number (ASCII value) and turns it back into a character.

It does the opposite of ord(), which converts a character into its number.

print(chr(65))   # Output: A
print(chr(97))   # Output: a
print(chr(33))   # Output: !
Character ASCII Value
space 32
... ...
a 97
b 98
c 99
... ...
A 65
B 66
C 67
... ...

Code examples

# Caesar Cipher
password = "abc"
encrypted_password = ""
for i in range(len(password)):
    # Get the character at position i
    letter = password[i]

    # Get the ASCII value of the letter
    ascii_val = ord(letter)

    # Add 1 to the ASCII value
    shifted_val = ascii_val + 1

    # Convert the new value back to a character
    new_char = chr(shifted_val)

    # Add the new character to the result
    encrypted_password = encrypted_password + new_char

print(new_password)  # Output: bcd
import random

password = ""

for i in range(8):  # Create a password with 8 characters
    ascii_value = random.randint(33, 126)  # Random visible characters
    password = password + chr(ascii_value)

print("Your random password is:", password)

Key points

  • chr() converts a number (ASCII value) into a single character

  • Useful for decoding, creating letters, or working with basic encryption

  • Works well with ord() to go back and forth between characters and numbers