Python Play Encoding (Unicode, UTF8, unicodedata)


  1. 說明
  2. Play with Python
    1. Get Code Point
    2. HTML Entity
    3. Get Bytes And Encoding

玩轉 Python Encoding,深入淺出驗證 Encoding 轉換,包含 UTF-8、Big5 等常見編碼。

logo

說明

如何確認 Python 的預設 Encoding

import sys
sys.getdefaultencoding()


項目 數值
字元
Code Point U+8CC7
Code Point Decimal 36039
Big5 B8EA
UTF-8 Encoding 0xE8 0xB3 0x87
UTF-16 Encoding 0x8CC7
UTF-32 Encoding 0x00008CC7
HTML Entity 1 資
HTML Entity 2 資

0x8CC7 = 8 * 16^3 + 12 * 16^2 + 12 * 16^1 + 7 * 16^0 = 36039

More About Unicode



項目 數值
字元
Code Point U+597D
Code Point Decimal 22909
Big5 A66E
UTF-8 Encoding 0xE5 0xA5 0xBD
UTF-16 Encoding 0x597D
UTF-32 Encoding 0x0000597D
HTML Entity 1 好
HTML Entity 2 好

0X597D = 5 * 16^3 + 9 * 16^2 + 7 * 16^1 + 13 * 16^0 = 22909

More About Unicode

Play with Python

Get Code Point

ord('資')
36039

hex(ord('資'))
'0x8cc7'

HTML Entity

Decimal 與 Hex 的 CodePoint 都可以下列方式表示 HTML Entity,並且透過 python 的 html.unescape 來轉回。

html.unescape(‘資’)
html.unescape(‘資’)

Get Bytes And Encoding

藉由 bytes 取得字元的 encoding,相同字元依照 encoding 方式不同,得到不同的 bytes。

bytes('資', 'big5')
b'\xb8\xea'

bytes('資', 'utf8')
b'\xe8\xb3\x87'

bytes('資', 'big5').hex()
'b8ea'

bytes('資', 'utf8').hex()
'e8b387'

字元 ‘好’ 的 bytes 是一個有趣的案例,使用 n 來表示 6e,搭配 hex 可以還原為完整的 a66e。

bytes('好', 'big5')
b'\xa6n'

hex(ord('n'))
'0x6e'

bytes('好', 'big5').hex()
'a66e'

python 預設為 Little-Endian, LE,可以指定為 Big-Endian, BE 以與 Code Point 顯示方式相同。

'資'.encode('utf-16')
b'\xff\xfe\xc7\x8c'

'資'.encode('utf-16-le')
b'\xc7\x8c'

'資'.encode('utf-16-be')
b'\x8c\xc7'

如果要取得 Unicode Character 的 Name,可以透過 python unicodedata library 來處理,並且可以透過 lookup 的方式將 name 還原為原本的字元 😀

import unicodedata

unicodedata.name('A')
# 'LATIN CAPITAL LETTER A'

unicodedata.name('資')
# 'CJK UNIFIED IDEOGRAPH-8CC7'

name = unicodedata.name('!')
# 'EXCLAMATION MARK'

unicodedata.lookup(name)
# '!'