ord()

The built-in ord() function returns the Unicode code point for a given character. It takes a single character as an argument and returns its integer representation in the Unicode table:

Python
>>> ord("A")
65

ord() Signature

Python Syntax
ord(c)

Arguments

Argument Description
c A single character

Return Value

  • Returns an integer representing the Unicode code point of the character.

ord() Examples

With the uppercase letter "B" as an argument:

Python
>>> ord("B")
66

With the lowercase letter "x" as an argument:

Python
>>> ord("x")
120

With the character "ñ" as an argument:

Python
>>> ord("ñ")
241

ord() Common Use Cases

The most common use cases for the ord() function include:

  • Encoding characters into their Unicode code points
  • Implementing basic cryptographic techniques
  • Validating input characters

ord() Real-World Example

Let’s consider a function that checks whether all characters in a string are uppercase letters of the English alphabet. This function uses ord() to ensure each character’s code point falls within the range for uppercase letters:

Python
>>> def is_uppercase(text):
...     for char in text:
...         if not (65 <= ord(char) <= 90):
...             return False
...     return True
...

>>> is_uppercase("HELLO")
True

>>> is_uppercase("Hello")
False

In this example, the ord() function helps determine if each character’s code point is within the range for uppercase letters (65 to 90), allowing the function to validate the string.

Tutorial

Unicode & Character Encodings in Python: A Painless Guide

In this tutorial, you'll get a Python-centric introduction to character encodings and unicode. Handling character encodings and numbering systems can at times seem painful and complicated, but this guide is here to help with easy-to-follow Python examples.

advanced python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader