Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 ord() Function

The Python ord() function

Python3 Built-in Functions Python3 built-in 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

- Type: character (a string of length 1) - Description: the character whose Unicode code point is wanted.

Function description


Example

Example 1: basic usage

Example

English letters

print

(

ord

(

'A'

)

)

 

Output: 65

print

(

ord

(

'Z'

)

)

 

Output: 90

print

(

ord

(

'a'

)

)

 

Output: 97

print

(

ord

(

'z'

)

)

 

Output: 122

Digit

print

(

ord

(

'0'

)

)

 

Output: 48

print

(

ord

(

'9'

)

)

 

Output: 57

Common symbols

print

(

ord

(

'!'

)

)

 

Output: 33

print

(

ord

(

'@'

)

)

 

Output: 64

Chinese

print

(

ord

(

'Center'

)

)

 

Output: 20013

print

(

ord

(

'Wen' (a Chinese character)

)

)

 

Output: 25991

print

(

ord

(

'Ni' (a Chinese character)

)

)

 

Output: 20320

Space

print

(

ord

(

' '

)

)

 

Output: 32

Expected output:

65
90
97
122
48
57
33
64
20013
25991
20320
32

Code analysis:

  1. The Unicode code points of uppercase letters A-Z are 65-90.
  2. The Unicode code points of lowercase letters a-z are 97-122.
  3. 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()

print

(

chr

(

ord

(

'A'

)

)

)

 

Output: A

print

(

ord

(

chr

(

65

)

)

)

 

Output: 65

Character offset calculation

char

=

'A'

offset

=

3

new_char

=

chr

(

ord

(

char

)

)

print

(

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

)

)

%

26

)

       

else

:

            result +

=

c

   

return

result

print

(

caesar_encode

(

"ABC"

,

3

)

)

 

Output: DEF

print

(

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 Functions Python3 built-in function