In Python, ord(c) returns the Unicode code point of the single character c as an int: ord("A") is 65 and ord("a") is 97. For ASCII characters this is the familiar ASCII value.
It is the inverse of chr(). ord() also accepts a bytes or bytearray object of length 1 and returns that byte's value.
ord() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Pass exactly one character.
python
code_point = ord(character)
Call
What it does
ord("A")
Returns 65.
ord("\n")
Returns 10.
ord("\u00e9")
Returns 233.
ord(b"A")
Returns 65 for a one-byte bytes object.
To get the code points of a whole string, use a loop or [ord(c) for c in text]; list(text.encode()) gives bytes instead, which differ for non-ASCII text.
Library declarations
python
ord(c, /)
# c: str of length 1, or bytes/bytearray of length 1
Parameters
Parameter
Description
c
Required. A string of exactly one character, or a bytes/bytearray of length 1.
Return Value
Return Value
Description
int
The code point (0 to 1,114,111), or the byte value (0 to 255).
Python Examples
Example 1 — Code Points of Common Characters
Print the number behind a capital letter, a lowercase letter, a digit, a space, and a newline.
python
for ch in ["A", "a", "0", " ", "\n"]:
print(repr(ch), ord(ch))
Output
'A' 65
'a' 97
'0' 48
' ' 32
'\n' 10
How It Works
One character each. Every item in the list is a string of length 1, which is what ord() requires.
ASCII values. Letters, digits, and the space have the same numbers as in the ASCII table.
Escape sequences."\n" is a single newline character with code point 10.
repr for clarity. Printing repr(ch) shows the space and newline instead of invisible output.
Example 2 — Digit Values, Letter Positions, and Sorting
Use differences between code points to read digits and letter positions, and sort by raw code point.
python
def digit_value(ch):
return ord(ch) - ord("0")
def letter_position(ch):
return ord(ch.lower()) - ord("a") + 1
print([digit_value(d) for d in "2024"])
print(letter_position("C"), letter_position("z"))
print(ord("a") - ord("A"))
print(sorted(["b", "B", "a", "A"], key=ord))
Output
[2, 0, 2, 4]
3 26
32
['A', 'B', 'a', 'b']
How It Works
Digits are consecutive. "0" to "9" are 48 to 57, so subtracting ord("0") gives each digit's value.
Letters are consecutive. Lowercasing first and subtracting ord("a") gives C = 3 and z = 26.
Case gap. Lowercase letters sit exactly 32 code points after their uppercase forms.
Sort by code point.key=ord puts all capitals (65, 66) before lowercase letters (97, 98).
Example 3 — Non-ASCII Characters, Bytes, and Errors
Look up code points beyond ASCII, read a byte value, and see what happens with two characters.