Python ord Function: Character to Integer
python ord function: Learn how to use Python's ord() to get Unicode code points from characters, handle errors, and apply it in real code.
python ord function requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.
When you need to convert a single character into its numeric Unicode code point in Python, the built-in ord() function is the direct tool. It takes a one-character string and returns an integer representing that character's Unicode code point. For example, ord('A') returns 65, and ord('€') returns 8364. This function is the inverse of chr(), which converts an integer back to a character.
What ord() Returns and Its Signature
The syntax is straightforward: ord(c) where c is a string of length exactly 1. The return value is an integer between 0 and 0x10FFFF (the maximum Unicode code point). The function works with any Unicode character, not just ASCII. For instance, ord('😀') returns 128512. Because Python 3 strings are sequences of Unicode code points, ord() always interprets the argument as a Unicode character, regardless of how it was encoded in memory.
Basic Usage and Examples
A minimal example:
print(ord('A')) # 65 print(ord('a')) # 97 print(ord('0')) # 48
If you need to process each character in a larger string, iterate over it and call ord() per character:
text = "hello" code_points = [ord(ch) for ch in text] print(code_points) # [104, 101, 108, 108, 111]
This pattern is common when you need to serialize text into numeric values, such as for custom hashing or encoding schemes. Note that ord() expects exactly one character; passing an empty string or a multi-character string raises a TypeError.
Common Errors and How to Avoid Them
The most frequent mistake is passing a string longer than one character. ord('ab') raises TypeError: ord() expected a character, but string of length 2 found. Similarly, passing a non-string type, like an integer, raises TypeError: ord() expected string of length 1, but int found. To handle these cases gracefully, you can validate input before calling ord():
def safe_ord(char): if isinstance(char, str) and len(char) == 1: return ord(char) raise ValueError("Expected a single character string")
In performance-sensitive code, the overhead of such a check is negligible compared to the cost of an unhandled exception. If you are processing user input, it's often better to sanitize the input earlier rather than relying on ord() to fail.
Practical Use Cases for ord()
One common use is character classification. Since code points for digits, uppercase letters, and lowercase letters are contiguous ranges in Unicode, you can check ranges without importing additional modules:
def is_digit(ch): return ord('0') <= ord(ch) <= ord('9')
Another use is generating character sequences. For example, to produce a range of letters:
uppercase = [chr(code) for code in range(ord('A'), ord('Z') + 1)]
ord() also appears in sorting or comparison logic when you need to compare characters by their numeric value. For instance, you might sort a list of strings by their first character's code point, though Python's default string comparison already does this lexicographically. A more direct use is when you need to convert a character to its ASCII value for a legacy protocol or a simple checksum.
ord() vs chr(): Inverse Operations
chr() and ord() are exact inverses. chr(65) returns 'A', and ord('A') returns 65. This round-trip is reliable for any valid Unicode code point:
char = 'λ' code = ord(char) restored = chr(code) assert char == restored
This property is useful when you need to store or transmit characters as integers and later reconstruct them. However, be aware that not every integer is a valid Unicode code point; chr() raises ValueError for values outside the valid range. When reading untrusted numeric data, validate the range before calling chr().
Unicode Code Points and Multi-byte Characters
A key detail is that ord() returns the Unicode code point, not the UTF-8 byte sequence. For characters outside the ASCII range, the code point is a single integer that may be larger than 255. For example, ord('é') returns 233, but 'é'.encode('utf-8') produces two bytes b'\xc3\xa9'. If you need byte values, you must encode the string first and then iterate over the bytes. This distinction matters when interfacing with binary protocols or low-level data structures.
In Python 2, ord() behaved differently for byte strings: it returned the byte value directly. In Python 3, strings are always Unicode, so ord() always returns the code point. If you are maintaining code that must run on both versions, be explicit about whether you are working with text or bytes.
Performance and Compatibility Considerations
ord() is a built-in implemented in C, so it is extremely fast and has no meaningful performance overhead. The operation is O(1) regardless of the character's code point. For bulk conversions, using a list comprehension or map(ord, text) is efficient and idiomatic.
Compatibility is straightforward in Python 3: ord() is available without any import. The main compatibility concern is the Python 2 vs 3 behavior for byte strings, as mentioned earlier. In modern codebases, you should ensure that you are passing a str object, not a bytes object, to avoid confusion. If you receive bytes from an external source, decode them to a string first using the appropriate encoding, then apply ord().
A final practical tip: when you need to compare characters across different scripts, remember that Unicode code points are not always aligned with alphabetical order. For locale-aware sorting, use the locale module or third-party libraries like PyICU instead of relying on raw ord() values. For most technical tasks, however, ord() provides a simple and reliable way to work with characters as numbers.