ord()
The built-in ord() function returns the ordinal value of a character. When given a one-character string, it returns the character’s Unicode code point. When given a bytes or bytearray object of length 1, it returns the corresponding byte value as an integer:
>>> ord("A")
65
ord() Signature
ord(character, /)
Arguments
| Argument | Description |
|---|---|
character |
A one-character string, or a bytes or bytearray object of length 1 |
Return Value
- Returns an integer: the Unicode code point of the character when the argument is a one-character string, or the byte value when the argument is a
bytesorbytearrayof length 1.
ord() Examples
With the uppercase letter "B" as an argument:
>>> ord("B")
66
With the lowercase letter "x" as an argument:
>>> ord("x")
120
With the character "ñ" as an argument:
>>> 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
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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python Built-in Functions: A Complete Guide (Tutorial)
- Strings and Character Data in Python (Tutorial)
- Unicode in Python: Working With Character Encodings (Course)
- Python Built-in Functions: A Complete Guide (Quiz)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)