1. 程式人生 > 其它 >python3 編碼與解碼

python3 編碼與解碼

import binascii
import sys

"""
python3:
python3預設編碼為unicode,由str型別進行表示。二進位制資料使用byte型別表示
字串通過編碼轉換成位元組碼,位元組碼通過解碼成為字串
encode:str –> bytes
decode:bytes – > str

轉:https://www.jianshu.com/p/c6a3a0167ff9
"""

print("print1:", sys.getdefaultencoding())

name = "中國"
name = name.encode("utf-8")
print(name)
print("print2:", type(name), name)
name = name.decode("utf-8")
name = name.encode("gbk")
print("print4:", type(name), name)


a = 'worker'.encode()
#先把worker轉換成二進位制資料然後在用十六進位制表示
b = binascii.b2a_hex(a) # w對應ascII是0x77;o對應ascII是0x6f...以此類摧
print(b)
#與b2a_hex相反
print(binascii.a2b_hex(b))
#這個功能和b2a_hex()一樣
c = binascii.hexlify(a)
print(c)
#這個功能和a2b_hex()一樣
print(binascii.unhexlify(c))

  

編碼與解碼:相當於計算機儲存資料【二進位制 十六進位制】與實際螢幕顯示的相互轉譯;

通用編碼: uft-8 utf-16

中文:gbk gb2132

注:

** 編碼與解碼與系統無關,是通用的規則;

**資料傳輸過程中不同語言和框架可以對資料進行拆解與整合,類似加密,而非編碼方式導致資料不可解讀