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:
>>> ord("A")
65
ord()
Signature
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:
>>> 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
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:
>>> 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's Built-in Functions: A Complete Exploration (Tutorial)
- Strings and Character Data in Python (Tutorial)
- Unicode in Python: Working With Character Encodings (Course)
- Python's Built-in Functions: A Complete Exploration (Quiz)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)