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.
Example
#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}")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
#ord(c)Parameters
#c
str of length 1
A single character.
More examples
#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))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.
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)Good practices
#- To sort without case sensitivity, use
key=str.lower. Full locale-correct sorting, with accented letters in the right place, needs thelocalemodule 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
#- chr()Returns the character for the given Unicode code point, e.g. chr(65) is "A". The opposite of ord().
- sorted()Returns a new, sorted list built from the items of any collection.
- str()Converts a value to a string.
- str.lower()Returns a copy of the string written in lowercase letters.
- int()Converts a value to an integer.
Spotted a mistake or missing an example? Write to us.