為什么需要本文,因為在對接某些很老的接口的時候,需要傳遞過去的是16進(jìn)制的hex字符串,并且要求對傳的字符串做編碼,這里就介紹了utf-8 Unicode bytes 等等。
#英文使用utf-8 轉(zhuǎn)換成16進(jìn)制hex字符串的方法newstr = 'asd'b_str = bytes(newstr,encoding='utf-8')print(b_str)hex_str = b_str.hex() #將bytes類型轉(zhuǎn)換成16進(jìn)制的hex字符串print(hex_str) #字節(jié)碼轉(zhuǎn)16進(jìn)制hex的方法print(bytes.fromhex(hex_str).decode('utf-8')) #將16進(jìn)制hex字符串轉(zhuǎn)換成bytes,然后在轉(zhuǎn)換成字符串print(type('中文'.encode('utf-8')),'中文'.encode('unicode_escape'),'中文123456'.encode('unicode_escape').decode('utf-8'))#中文轉(zhuǎn)換成Unicode的一種方法之一u_str = '中文123456'b_str = bytes(u_str,encoding='unicode_escape')h_u_s = b_str.hex()print ("/u4e2d/u6587") #Unicode編碼可直接輸出#中文使用Unicode轉(zhuǎn)換成bytes再轉(zhuǎn)換成16進(jìn)制hex方法 包含英文和數(shù)字u_cn = '中文asd123'hex_msg = bytes(u_cn,encoding='utf_16_be').hex() #這是特殊要求下最終的解決方案#注意在Python3中已經(jīng)沒有了直接將字符串變成bytes或者Unicode的方法了#也就是說,在Python中 u'中文'已經(jīng)不再奏效#bytes轉(zhuǎn)strb_str = bytes('中文',encoding='utf-8')print(b_str.decode()) #直接輸出為普通字符串以上這篇Python3編碼問題 Unicode utf-8 bytes互轉(zhuǎn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答