Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python ord() function

Reference for Python ord(): get the Unicode code point of a single character, the inverse of chr(), with examples for letters, digits, emoji and bytes.

The built-in ord() function takes a string of length one and returns its Unicode code point as an integer. It is the inverse of chr(): chr(ord(c)) == c for every character c.

For plain ASCII, the code points match the ASCII table: ord("A") is 65 and ord("a") is 97. For other scripts and emoji the values are larger, up to 1,114,111 (0x10FFFF).

Python
ord("A")    # 65
ord("รฉ")    # 233
ord("๐Ÿ˜€")   # 128512

Try it

Python Characters to numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A tiny Caesar cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
ord(c)
Name Description
c A string of exactly one character, or a bytes/bytearray object of length one.

Return value: an int between 0 and 1,114,111.

Raises: TypeError if the argument does not have length one (an empty string, a longer string, or a non-string).

Usage notes

  • One character only. ord("ab") and ord("") raise TypeError. To convert a whole string, loop or use [ord(c) for c in text].
  • Code points, not bytes. The result is the Unicode number, not how the character is stored. "โ‚ฌ" has code point 8364 but takes three bytes in UTF-8; use .encode("utf-8") for bytes.
  • Bytes input gives the byte value: ord(b"A") is 65.
  • Characters made of several code points (such as an emoji with a skin tone, or e plus a combining accent) are several str characters, so ord needs them split first.
  • Ordering. Comparing letters with < follows code points, so uppercase letters sort before lowercase ones.
  • Digit characters: ord(d) - ord("0") converts a digit character to its value, although int(d) is clearer (and also handles non-ASCII digits).
  • Inverse: use chr() to go from number back to character.