[5 min python] 內建函數 - ord()

更新 發佈閱讀 7 分鐘

Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。

ord():把字元變成對應的數字

ord() 接收一個字元(長度為 1 的字串),回傳它的 Unicode 碼位(整數)。

語法:

ord(c)  # c 是長度為 1 的字串

基本用法:

print(ord('A'))    # 65
print(ord('a'))    # 97
print(ord('0'))    # 48
print(ord(' '))    # 32(空格)
print(ord('\n'))   # 10(換行)

每個字元在 Unicode 中都有一個唯一的數字編號,ord() 就是用來查這個編號的。

搭配 chr() 互相轉換

ord() 和 chr() 是一對互逆函數。ord() 把字元變數字,chr() 把數字變字元:

print(chr(ord('Z')))   # Z(轉回來)
print(ord(chr(100)))    # 100(轉回來)

# 把字元往後移 1 位
print(chr(ord('A') + 1))  # B
print(chr(ord('a') + 1))  # b

用 ord() 判斷字元類型

利用 Unicode 碼位的範圍,可以手動判斷字元屬於哪種類型:

def char_type(c):
    code = ord(c)
    if 48 <= code <= 57:
        return '數字'
    elif 65 <= code <= 90:
        return '大寫字母'
    elif 97 <= code <= 122:
        return '小寫字母'
    else:
        return '其他字元'

print(char_type('A'))  # 大寫字母
print(char_type('5'))  # 數字
print(char_type('z'))  # 小寫字母
print(char_type('!'))  # 其他字元

當然,Python 有內建的 str.isdigit()、str.isupper() 等方法更方便,但理解 ord() 的原理有助於解決更複雜的問題。

ord() 處理中文和 emoji

ord() 不只能處理 ASCII 字元,任何單一 Unicode 字元都行:

print(ord('你'))    # 20320
print(ord('好'))    # 22909
print(ord('♥'))    # 9829
print(ord('😊'))   # 128522

注意:ord() 只接受長度為 1 的字串,傳入多個字元會報錯:

# ord('AB')  # TypeError: ord() expected a character, but string of length 2 found
# ord('')    # TypeError: ord() expected a character, but string of length 0 found

用 ord() 計算字母距離

因為字母在 Unicode 中是連續排列的,可以用 ord() 來計算兩個字母之間的距離:

# 計算字母是第幾個(A=1, B=2, ...)
def letter_position(c):
    return ord(c.upper()) - ord('A') + 1

print(letter_position('A'))  # 1
print(letter_position('Z'))  # 26
print(letter_position('m'))  # 13

小小綜合例子

來做一個字串的 ASCII 藝術分析器,統計每個字元的 Unicode 碼位並視覺化:

# 字元碼位分析器
def analyze_string(text):
    print(f'分析字串:"{text}"')
    print('-' * 40)
    for c in text:
        code = ord(c)
        bar = '█' * (code // 10)
        print(f"'{c}' → {code:>6d} {bar}")
    
    codes = [ord(c) for c in text]
    print('-' * 40)
    print(f'最小碼位:{min(codes)} ({chr(min(codes))})')
    print(f'最大碼位:{max(codes)} ({chr(max(codes))})')
    print(f'碼位總和:{sum(codes)}')

analyze_string('Hello!')
# 輸出:
# 分析字串:"Hello!"
# ----------------------------------------
# 'H' →     72 ███████
# 'e' →    101 ██████████
# 'l' →    108 ██████████
# 'l' →    108 ██████████
# 'o' →    111 ███████████
# '!' →     33 ███
# ----------------------------------------
# 最小碼位:33 (!)
# 最大碼位:111 (o)
# 碼位總和:533
留言
avatar-img
艾利斯幻想旅程
5會員
467內容數
網路世界是一個充滿多元性與無限可能的空間,人們可以在此分享資訊、交流思想,並展現無盡的創造力。然而,隨著社交媒體和線上論壇的普及,一種有趣且獨特的現象也隨之興起——廢文。廢文指的是那些內容看似無聊、無害,或表面上毫無意義的帖子、留言或圖片,通常目的在於娛樂或逗趣,而非提供實質價值的資訊。
艾利斯幻想旅程的其他內容
2026/02/21
Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。 chr():把數字變成對應的字元 chr() 接收一個整數(Unicode 碼位),回傳對應的字元。 語法: chr(
2026/02/21
Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。 chr():把數字變成對應的字元 chr() 接收一個整數(Unicode 碼位),回傳對應的字元。 語法: chr(
2026/02/21
Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。 all():全部為真才回傳 True 語法: all(iterable) all() 會檢查可迭代物件中是否「全部」元
2026/02/21
Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。 all():全部為真才回傳 True 語法: all(iterable) all() 會檢查可迭代物件中是否「全部」元
2026/02/21
Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。 any():任一為真就回傳 True 語法: any(iterable) any() 會檢查可迭代物件中是否「至少有一
2026/02/21
Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。 any():任一為真就回傳 True 語法: any(iterable) any() 會檢查可迭代物件中是否「至少有一
看更多