Python ord() Function

Python3 内置函数Python3 Built-in Functions


ord()is a built-in function in Python used to obtain the Unicode code point of a character.

ord()It accepts a character (a string of length 1) and returns its corresponding Unicode code point (integer). It ischr()the inverse function of chr().

Word Definition: ordYesordinalAbbreviation of (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 to be obtained.

Function Description

  • Return Value: Returns an integer representing the Unicode code point of the character.

Examples

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

# Numbers
print(ord('0'))   # Output: 48
print(ord('9'))   # Output: 57

# Common symbols
print(ord('!'))   # Output: 33
print(ord('@'))   # Output: 64

# Chinese characters
print(ord('middle'))  # Output: 20013
print(ord('language'))  # Output: 25991
print(ord('you'))  # Output: 20320

# Space
print(ord(' '))   # Output: 32

Expected output:

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

Code analysis:

  1. Uppercase letters A-Z have Unicode code points 65-90.
  2. Lowercase letters a-z have Unicode code points 97-122.
  3. Chinese characters typically have Unicode code points greater than 19968 (0x4E00).

Example 2: Working with chr()

Example

# ord() is the inverse function 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) + offset)
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) - base + shift) % 26 + base)
        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()andchr()Used together, they can be applied in scenarios such as character encoding conversion and cryptography.


Python3 内置函数Python3 Built-in Functions


Other Extensions