Python ord() Function: Character to Unicode Code Point

Core Purpose & Overview

The built-in ord() function takes a single Unicode character as input and returns an integer representing its underlying Unicode code point. For the first 128 characters (0 through 127), the returned values match standard ASCII values.

Key Complement: ord() is the exact inverse of chr(), which converts an integer code point back into its character representation (chr(ord('A')) == 'A').

Syntax & Parameters 🔝

ord(c)
ParameterTypeRequirementDescription
c str (or bytes/bytearray of length 1) Required A string of length exactly 1 representing a single Unicode character.
Return Value int — An integer representing the character's code point (range: 0 to 1,114,111 / 0x10FFFF).

Basic ASCII Examples: Letters, Digits & Symbols 🔝

For standard alphanumeric characters and keyboard symbols, ord() returns their standard 7-bit ASCII decimal values:

# 1. Uppercase and lowercase ASCII letters
print("ord('A'):", ord("A"))   # Output: 65
print("ord('a'):", ord("a"))   # Output: 97

# 2. Digits (note: '0' has ASCII code 48, not 0)
print("ord('0'):", ord("0"))   # Output: 48
print("ord('9'):", ord("9"))   # Output: 57

# 3. Punctuation and symbols
print("ord('#'):", ord("#"))   # Output: 35
print("ord('$'):", ord("$"))   # Output: 36
print("ord(' '):", ord(" "))   # Output: 32 (space)

The Inverse Relationship with chr() 🔝

ord() and chr() are exact mathematical inverses:

  • ord(c) maps a character → integer.
  • chr(i) maps an integer → character.
char = "Z"
code_point = ord(char)
restored_char = chr(code_point)

print(f"Character: {char} -> Code Point: {code_point}")
print(f"chr({code_point}) restored: {restored_char}")
print("Are they identical?", restored_char == char)

Output:

Character: Z -> Code Point: 90
chr(90) restored: Z
Are they identical? True

Unicode Code Points: Symbols, Non-Latin & Emojis 🔝

Because Python 3 strings natively support Unicode, ord() works seamlessly across all international scripts, mathematical symbols, and emojis:

# 1. Currency and international symbols
print("Euro symbol '€':", ord("€"))          # Output: 8364 (U+20AC)
print("Greek capital Omega 'Ω':", ord("Ω"))   # Output: 937 (U+03A9)

# 2. Devanagari script
print("Devanagari 'अ':", ord("अ"))            # Output: 2309 (U+0905)

# 3. Unicode Emoji (single code point)
print("Smiley '😊':", ord("😊"))              # Output: 128522 (U+1F60A)

Common Pitfalls & TypeError Handling 🔝

ord() strictly expects a string of length 1. Passing an empty string or a multi-character string raises a TypeError:

# Error 1: String of length 2
try:
    ord("ab")
except TypeError as e:
    print("Length 2 Error:", e)

# Error 2: Empty string (length 0)
try:
    ord("")
except TypeError as e:
    print("Length 0 Error:", e)

Output:

Length 2 Error: ord() expected a character, but string of length 2 found
Length 0 Error: ord() expected a character, but string of length 0 found

Practical Applications: Generating Ranges & Case Shifts 🔝

1. Generating Alphabet Lists Dynamically

Instead of manually typing all 26 letters of the alphabet, use ord() and chr() inside a list comprehension:

alphabet_upper = [chr(i) for i in range(ord("A"), ord("Z") + 1)]
print("Generated Alphabet:", alphabet_upper[:8], "...", alphabet_upper[-3:])

2. Case Conversion Using ASCII Offsets

The difference between lowercase 'a' (97) and uppercase 'A' (65) is exactly 32. Subtracting 32 from a lowercase code point converts it to uppercase without calling string helper methods:

raw_text = "Welcome to Python!"
uppercase_text = []

for char in raw_text:
    code = ord(char)
    if 97 <= code <= 122:  # 'a' through 'z'
        uppercase_text.append(chr(code - 32))
    else:
        uppercase_text.append(char)

print("".join(uppercase_text))  # Output: WELCOME TO PYTHON!

Hands-on Exercise: Caesar Cipher with Assertions 🔝

Build a Caesar Cipher encryption function that shifts letters forward by $k$ positions while preserving letter casing and punctuation. Verify encryption and decryption with unit assertions:

def caesar_cipher(text: str, shift: int = 3) -> str:
    result = []
    for char in text:
        if "A" <= char <= "Z":
            # Shift uppercase within range 65..90
            result.append(chr((ord(char) - ord("A") + shift) % 26 + ord("A")))
        elif "a" <= char <= "z":
            # Shift lowercase within range 97..122
            result.append(chr((ord(char) - ord("a") + shift) % 26 + ord("a")))
        else:
            result.append(char)
    return "".join(result)

# Test with shift 3
original_msg = "Hello, World!"
encrypted_msg = caesar_cipher(original_msg, shift=3)
decrypted_msg = caesar_cipher(encrypted_msg, shift=-3)

assert encrypted_msg == "Khoor, Zruog!"
assert decrypted_msg == original_msg

print("Original:", original_msg)
print("Encrypted (+3):", encrypted_msg)
print("Decrypted (-3):", decrypted_msg)
print("All unit assertions passed successfully!")



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer