為什麼需要本文,因為在對接某些很老的接口的時候,需要傳遞過去的是16進制的hex字元串,并且要求對傳的字元串做編碼,這裡就介紹了utf-8 Unicode bytes 等等。
#英文使用utf-8 轉換成16進制hex字元串的方法
newstr = 'asd'
b_str = bytes(newstr,encoding='utf-8')
print(b_str)
hex_str = b_str.hex() #将bytes類型轉換成16進制的hex字元串
print(hex_str) #位元組碼轉16進制hex的方法
print(bytes.fromhex(hex_str).decode('utf-8')) #将16進制hex字元串轉換成bytes,然後在轉換成字元串
print(type('中文'.encode('utf-8')),'中文'.encode('unicode_escape'),'中文123456'.encode('unicode_escape').decode('utf-8'))
#中文轉換成Unicode的一種方法之一
u_str = '中文123456'
b_str = bytes(u_str,encoding='unicode_escape')
h_u_s = b_str.hex()print ("\u4e2d\u6587") #Unicode編碼可直接輸出
#中文使用Unicode轉換成bytes再轉換成16進制hex方法 包含英文和數字
u_cn = '中文asd123'
hex_msg = bytes(u_cn,encoding='utf_16_be').hex()
#這是特殊要求下最終的解決方案
#注意在Python3中已經沒有了直接将字元串變成bytes或者Unicode的方法了
#也就是說,在Python中 u'中文'已經不再奏效
#bytes轉str
b_str = bytes('中文',encoding='utf-8')
print(b_str.decode()) #直接輸出為普通字元串
以上這篇Python3編碼問題 Unicode utf-8 bytes互轉方法就是小編分享給大家的全部内容了,希望能給大家一個參考,也希望大家多多支援聚米學院。