Convert Between Characters and ASCII Codes in Python with chr() and ord()

Convert Between Characters and ASCII Codes in Python with chr() and ord() ๐Ÿ”ก

Python makes it easy to switch between characters and their numeric ASCII/Unicode representations using the built-in chr() and ord() functions. These are useful for encryption, sorting, character arithmetic, and more.

Python ASCII icon

✅ Character to ASCII: ord()

# Character → ASCII code
print(ord('A'))  # 65
print(ord('a'))  # 97

✅ ASCII to Character: chr()

# ASCII code → Character
print(chr(65))   # 'A'
print(chr(97))   # 'a' 

✅ Loop through the alphabet

# Print all uppercase letters A-Z
for i in range(ord('A'), ord('Z') + 1):
    print(chr(i), end=' ')  # A B C ... Z

✅ Simple Caesar cipher example

# Simple Caesar cipher (uppercase only)
def caesar_encrypt(text, shift):
    result = ''
    for char in text:
        if char.isupper():
            result += chr((ord(char) - 65 + shift) % 26 + 65)
        else:
            result += char
    return result

print(caesar_encrypt("HELLO", 3))  # KHOOR

chr() and ord() are core tools for any developer working with character data, encoding, or algorithms. They're also helpful in many Python coding interviews and challenges.

Every character has a number. Once you master chr() and ord(), you'll unlock powerful string manipulation in Python. ๐Ÿš€

Icons by Flaticon

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“