ord()

Returns the Unicode code point of a single character, e.g. ord("A") is 65. The opposite of chr().

Returns
An integer, the character’s code point in the Unicode standard.
On this page

Example

#
Python
print(ord("A"), ord("a"), ord("é"))
print(ord("c") - ord("a"))

for char in "Aé1":
    print(char, ord(char), f"U+{ord(char):04X}")
Resultsaved result, you can check it
65 97 233
2
A 65 U+0041
é 233 U+00E9
1 49 U+0031

Definition and usage

#

ord(char) takes a string made of exactly one character and returns its number in the Unicode standard. ord("A") is 65, ord("a") is 97, and ord("é") is 233. An empty string, or one longer than one character, raises a TypeError.

Python compares strings using exactly these codes, character by character. That is why uppercase letters are "smaller" than lowercase ones ("Z" < "a"), and accented letters end up at the end when sorting, after "z". Knowing the codes makes it easy to see where results like this come from.

You get the hexadecimal form of a code with hex(ord(char)), or an f-string f"U+{ord(char):04X}", in the format used in Unicode tables. Together with chr(), the function lets you do arithmetic on characters, for example finding a letter’s position in the alphabet: ord(letter) - ord("a").

Syntax

#
Syntax
ord(c)

Parameters

#
  • c

    str of length 1

    A single character.

More examples

#
Why sorting "breaks" accented words
Python
words = ["Zoo", "apple", "banana", "café", "naïve"]

print(sorted(words))
print(ord("Z"), ord("a"), ord("z"), ord("é"), ord("ï"))
print(sorted(words, key=str.lower))
Resultsaved result, you can check it
['Zoo', 'apple', 'banana', 'café', 'naïve']
90 97 122 233 239
['apple', 'banana', 'café', 'naïve', 'Zoo']

Uppercase letters have smaller codes than lowercase ones, and accented letters sit far beyond z, which is why they end up at the end of the list either way.

A letter’s position, and a string longer than one character
Python
def letter_position(letter):
    return ord(letter.lower()) - ord("a") + 1

print(letter_position("C"), letter_position("z"))

try:
    ord("ab")
except TypeError as error:
    print(error)
Resultsaved result, you can check it
3 26
ord() expected a character, but string of length 2 found

Good practices

#
  • To sort without case sensitivity, use key=str.lower. Full locale-correct sorting, with accented letters in the right place, needs the locale module or the PyICU library.
  • The codes of every character in a string: [ord(c) for c in text].
  • You can check a range of characters without ord() by comparing strings directly: the condition "a" <= char <= "z" gives the same result as comparing codes.

Related entries

#

Spotted a mistake or missing an example? Write to us.