When diving into programming with Python, you’ll quickly encounter situations where you need to work with characters and their corresponding numerical values. Whether you’re dealing with encryption, sorting, or just exploring how text is represented in computers, understanding the ord() and chr() functions is essential. These simple but powerful built-in functions allow you to effortlessly convert between characters and their Unicode code points.
What Are ord() and chr()?
The ord() and chr() functions are among the most straightforward tools in Python’s standard library for dealing with character encoding.
- ord(char): Takes a single Unicode character and returns its integer code point.
- chr(integer): Takes an integer and returns the corresponding Unicode character.
In simpler terms, ord() is the inverse of chr(), and vice versa.
Understanding Unicode and Character Encoding
Before digging deeper, it’s helpful to understand how Python treats characters behind the scenes. Characters in Python are represented using the Unicode standard. Each character is mapped to a unique number called a code point. For example:
- The character 'A'has the Unicode code point65.
- The character 'a'has the code point97.
- The character '🙂'has the code point128578.
These mappings are used internally by computers to store and manipulate text efficiently.
 
Using ord() in Python
The ord() function is used to retrieve the Unicode code point of a single character. It’s especially handy when performing operations that rely on the numerical representation of characters.
Syntax:
ord(character)Examples:
print(ord('A'))  # Output: 65
print(ord('a'))  # Output: 97
print(ord('0'))  # Output: 48
print(ord('🙂'))  # Output: 128578This function only accepts a single character as an argument. If you try to pass a string of more than one character, you’ll get a TypeError.
# This will raise an error
ord('Hello')  # TypeError: ord() expected a character, but string of length 5 foundUsing chr() in Python
The chr() function works in exactly the opposite way. It takes a code point (an integer) and returns the associated Unicode character.
Syntax:
chr(code_point)Examples:
print(chr(65))     # Output: 'A'
print(chr(97))     # Output: 'a'
print(chr(48))     # Output: '0'
print(chr(128578)) # Output: '🙂'Keep in mind that if you pass an integer that is outside the valid Unicode range (0 to 1,114,111), it will raise a ValueError.
# Invalid code point
chr(2000000)  # ValueError: chr() arg not in range(0x110000)Why Do These Functions Matter?
At a glance, ord() and chr() might seem limited in utility—but they’re foundational tools in many more advanced scenarios. Here are a few contexts where they’re incredibly useful:
- Sorting characters by Unicode order
- Encrypting and decrypting text (e.g., Caesar cipher)
- Generating ranges of letters programmatically
- Understanding the underlying data representation of text
 
Practical Examples Using ord() and chr()
1. Creating a Caesar Cipher
A Caesar cipher is one of the simplest and most well-known encryption techniques. It shifts each letter by a fixed number of positions in the alphabet.
def caesar_encrypt(text, shift):
    result = ''
    for char in text:
        if char.isalpha():
            base = ord('A') if char.isupper() else ord('a')
            shifted = (ord(char) - base + shift) % 26 + base
            result += chr(shifted)
        else:
            result += char
    return result
print(caesar_encrypt('Hello, World!', 3))  # Output: 'Khoor, Zruog!'2. Generating the Alphabet Using chr()
Want a list of all lowercase letters? No problem!
alphabet = ''.join([chr(i) for i in range(ord('a'), ord('z') + 1)])
print(alphabet)  # Output: 'abcdefghijklmnopqrstuvwxyz'3. Displaying Code Points for a Word
This quick snippet shows the Unicode values of each character in a word.
word = 'Python'
for char in word:
    print(f"{char} --> {ord(char)}")Python and Unicode: Going Beyond ASCII
Unlike some older languages like C, Python’s ord() and chr() are not limited to ASCII. You’re not restricted to English letters – emojis, symbols, and characters from hundreds of languages can all be handled seamlessly.
print(ord('€'))   # Output: 8364
print(chr(8364))  # Output: '€'
print(ord('中'))  # Output: 20013
print(chr(20013)) # Output: '中'When to Avoid Using ord() and chr()
While these functions are incredibly versatile, they’re not the best choice for all string-related tasks. If your goal is complex text parsing, encoding conversions (like UTF-8 to UTF-16), or multi-character manipulations, it’s better to use Python’s encode() and decode() methods or external libraries like unicodedata or codecs.
Final Thoughts
The ord() and chr() functions in Python might seem like simple utilities, but they are incredibly powerful when you understand how text is represented and manipulated under the hood. From building custom encryption algorithms to simply exploring how non-English characters are encoded, mastering these functions will enhance your understanding and capabilities as a Python programmer.
Next time you find yourself working with strings and characters, remember these trusty tools—they just might be the key to solving your problem.


 
		