為什么需要本文,因為在對接某些很老的接口的時候,需要傳遞過去的是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轉strb_str = bytes('中文',encoding='utf-8')print(b_str.decode()) #直接輸出為普通字符串
以上這篇Python3編碼問題 Unicode utf-8 bytes互轉方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答