Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python chr(): แปลง Unicode Code Point เป็น Character

ฟังก์ชัน chr() เป็น Built-in Function ที่ แปลง Integer (Unicode Code Point) เป็น Character (String ความยาว 1) เป็นคู่ของ ord() ที่ทำตรงข้าม

ไวยากรณ์

chr(i)  # i = Integer (0 <= i <= 0x10FFFF = 1,114,111)

ตัวอย่างพื้นฐาน

# ASCII Characters
print(chr(65))   # 'A'
print(chr(97))   # 'a'
print(chr(48))   # '0'
print(chr(32))   # ' ' (Space)
print(chr(33))   # '!'
print(chr(126))  # '~'

# Unicode Characters
print(chr(0x00E0))  # 'à' (Latin Small Letter A with Grave)
print(chr(0x0E01))  # 'ก' (Thai Character Ko Kai)
print(chr(0x3042))  # 'あ' (Hiragana A)
print(chr(0x1F600)) # '😀' (Emoji: Grinning Face)

# ตรวจสอบ Code Point
print(hex(ord('A')))    # 0x41
print(hex(ord('ก')))    # 0xe01
print(hex(ord('😀')))   # 0x1f600

ตัวอย่าง: สร้างสตริงจาก List ของ Code Points

# Method 1: Loop + Join
code_points = [84, 85, 84, 79, 82, 73, 65, 76, 83]  # TUTORIALS
result = ''.join(chr(cp) for cp in code_points)
print(result)  # TUTORIALS

# Method 2: bytes.decode (สำหรับ ASCII/UTF-8)
code_points = [72, 101, 108, 108, 111]  # Hello
result = bytes(code_points).decode('ascii')
print(result)  # Hello

# Method 3: Map
result = ''.join(map(chr, [84, 85, 84, 79, 82]))
print(result)  # TUTOR

ช่วง Unicode ที่น่าสนใจ

RangeNameExamples
0x0000-0x007FBasic Latin (ASCII)A-Z, a-z, 0-9, Symbols
0x0080-0x00FFLatin-1 SupplementÀ, á, ñ, ø, ß
0x0E00-0x0E7FThaiก, ข, ค, ง, ะ, ำ
0x3040-0x309FHiraganaあ, い, う, え, お
0x4E00-0x9FFFCJK Unified Ideographs中, 文, 日, 本
0x1F600-0x1F64FEmoticons (Emoji)😀, 😂, 😍, 😭, 😴
0x1F300-0x1F5FFMisc Symbols and Pictographs🌟, 🌈, 🎉, 🎁, 🚀

Error Handling

# Out of Range
try:
    chr(1_200_000)  # > 0x10FFFF
except ValueError as e:
    print(f"Error: {e}")  # chr() arg not in range(0x110000)

# Negative
try:
    chr(-1)
except ValueError as e:
    print(f"Error: {e}")  # chr() arg not in range(0x110000)

# Float
try:
    chr(65.5)
except TypeError as e:
    print(f"Error: {e}")  # 'float' object cannot be interpreted as an integer

การประยุกต์ใช้งาน

1. Generate Alphabet

# English Alphabet
uppercase = ''.join(chr(i) for i in range(ord('A'), ord('Z')+1))
lowercase = ''.join(chr(i) for i in range(ord('a'), ord('z')+1))
print(uppercase)  # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(lowercase)  # abcdefghijklmnopqrstuvwxyz

# Thai Consonants
thai_consonants = ''.join(chr(i) for i in range(0x0E01, 0x0E2E+1))
print(thai_consonants)  # กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮ

2. Simple Caesar Cipher

def caesar_cipher(text, shift):
    result = []
    for char in text:
        if char.isupper():
            # A=65, Z=90
            shifted = (ord(char) - ord('A') + shift) % 26 + ord('A')
            result.append(chr(shifted))
        elif char.islower():
            # a=97, z=122
            shifted = (ord(char) - ord('a') + shift) % 26 + ord('a')
            result.append(chr(shifted))
        else:
            result.append(char)
    return ''.join(result)

print(caesar_cipher("Hello World!", 3))  # Khoor Zruog!
print(caesar_cipher("Khoor Zruog!", -3)) # Hello World!

3. Print Unicode Table

def print_unicode_range(start, end, cols=16):
    """Print Unicode Characters in Range"""
    for i in range(start, end + 1):
        char = chr(i)
        # Print Code Point and Character
        print(f"U+{i:04X}: {char}", end='  ')
        if (i - start + 1) % cols == 0:
            print()
    print()

# Print Thai Vowels
print_unicode_range(0x0E30, 0x0E3A, cols=8)

สรุป

  • chr(i): Code Point → Character (String)
  • ord(c): Character → Code Point (Integer)
  • Range: 0 ถึง 1,114,111 (0x10FFFF)
  • ใช้สร้าง Alphabet, Cipher, Unicode Exploration, Emoji Generation
  • คู่ของ ord() - จดจำคู่กัน: ord = Ordinal (Number), chr = Character