In this article we’ll go through the Python ord function and it’s uses complete with several examples.
The ord()
function takes a single character, or string of length one as input and returns it’s corresponding Unicode value. For instance ord('a')
will return 97
, where 97
is the Unicode value representing a
. The ord() function can be thought of the reverse of the chr() function which takes a Unicode value and outputs it’s corresponding character.
You might also be interested in the ASCII table which stores the first 128 values of Unicode. It contains all the English alphabet and other basic symbols. For further information, here’s a link to an ASCII table which contains all 128 of it’s characters.
Examples
>>> ord('a')
97
>>> ord('A')
65
>>> ord('*')
42
>>> ord('$')
36
Here are some values which do not throw errors when passed into the ord function. The ord function only takes single characters or strings of length one!
>>> ord('AB')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
ord('AB')
TypeError: ord() expected a character, but string of length 2 found
>>> ord(5)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
ord(5)
TypeError: ord() expected string of length 1, but int found
This marks the end of the Python ord Function. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.
Here’s a link back to the main Python Built-in Functions page.