Character to ASCII

In Python, the ord() function converts a single character (letter, number, or symbol) into its ASCII value (a number that represents that character).

This is useful when you need to compare characters or build simple ciphers.

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

Code examples

letter = "M"
if ord(letter) >= 65 and ord(letter) <= 90:
    print("It’s uppercase")  # Output: It’s uppercase
char = "g"

if ord(char) >= 97 and ord(char) <= 122:
    print("It's lowercase")  # Output: It's lowercase
if ord("B") > ord("A"):
    print("B comes after A")  # Output: B comes after A
# 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

Key points

  • ord() only works with a single character

  • Useful for sorting, comparing, encoding, or checking character types

  • To convert a number back to a character, use chr()