為什么需要本文,因?yàn)樵趯?duì)接某些很老的接口的時(shí)候,需要傳遞過(guò)去的是16進(jìn)制的hex字符串,并且要求對(duì)傳的字符串做編碼,這里就介紹了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)沒(méi)有了直接將字符串變成bytes或者Unicode的方法了#也就是說(shuō),在Python中 u'中文'已經(jīng)不再奏效#bytes轉(zhuǎn)strb_str = bytes('中文',encoding='utf-8')print(b_str.decode()) #直接輸出為普通字符串
/////////////////////////////////////
#英文使用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)沒(méi)有了直接將字符串變成bytes或者Unicode的方法了
#也就是說(shuō),在Python中 u'中文'已經(jīng)不再奏效
#bytes轉(zhuǎn)str
b_str = bytes('中文',encoding='utf-8')
print(b_str.decode()) #直接輸出為普通字符串
聯(lián)系客服