The Python ord() function
ord() is a built-in Python function that gets a character's Unicode code point.
ord() It takes a character (a string of length 1) and returns its corresponding Unicode code point (an integer). It is the inverse of chr() .
Word meaning: ord Is ordinalis short for (ordinal).
Basic syntax and parameters
Syntax format
ord(c)
Parameter Description
- Parameter c:
- Type: character (a string of length 1)
- Description: the character whose Unicode code point is wanted.
Function description
- Return Value: Returns an integer representing the Unicode code point of the character.
Example
Example 1: basic usage
Example
English letters
(
ord
(
'A'
)
)
Output: 65
(
ord
(
'Z'
)
)
Output: 90
(
ord
(
'a'
)
)
Output: 97
(
ord
(
'z'
)
)
Output: 122
Digit
(
ord
(
'0'
)
)
Output: 48
(
ord
(
'9'
)
)
Output: 57
Common symbols
(
ord
(
'!'
)
)
Output: 33
(
ord
(
'@'
)
)
Output: 64
Chinese
(
ord
(
'Center'
)
)
Output: 20013
(
ord
(
'Wen' (a Chinese character)
)
)
Output: 25991
(
ord
(
'Ni' (a Chinese character)
)
)
Output: 20320
Space
(
ord
(
' '
)
)
Output: 32
Expected output:
65
90
97
122
48
57
33
64
20013
25991
20320
32
Code analysis:
- The Unicode code points of uppercase letters A-Z are 65-90.
- The Unicode code points of lowercase letters a-z are 97-122.
- The Unicode code points of Chinese characters are usually greater than 19968 (0x4E00).
Example 2: working with chr()
Example
ord() is the inverse of chr()
(
chr
(
ord
(
'A'
)
)
)
Output: A
(
ord
(
chr
(
65
)
)
)
Output: 65
Character offset calculation
char
=
'A'
offset
=
3
new_char
=
chr
(
ord
(
char
)
- offset
)
(
new_char
)
Output: D
Caesar cipher example
def
caesar_encode
(
text
,
shift
)
:
result
=
""
for
c
in
text:
if
c.
isalpha
(
)
:
base
=
ord
(
'A'
)
if
c.
isupper
(
)
else
ord
(
'a'
)
result +
=
chr
(
(
ord
(
c
)
- base + shift
)
%
26
- base
)
else
:
result +
=
c
return
result
(
caesar_encode
(
"ABC"
,
3
)
)
Output: DEF
(
caesar_encode
(
"XYZ"
,
3
)
)
Output: ABC
Expected output:
A
65
D
DEF
ABC
ord() and chr() Together they can be used for character encoding conversion, cryptography and similar scenarios.
Python3 built-in function