Python3编码问题 Unicode utf-8 bytes互转方法

yipeiwu_com6年前Python基础

为什么需要本文,因为在对接某些很老的接口的时候,需要传递过去的是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互转方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3 Post登录并且保存cookie登录其他页面的方法

如下所示: import urllib.request import sys import http.cookiejar import urllib.parse from bs4 i...

python去除拼音声调字母,替换为字母的方法

第一种方法 import sys import unicodedata s = "Lǐ Zhōu Wú" remap = { # ord返回ascii值 ord('\t'): '...

python多线程调用exit无法退出的解决方法

python启用多线程后,调用exit出现无法退出的情况,原因是exit会抛出Systemexit的异常,如果在exit外围调用了try,就会出现ctrl+c两次才能退出的情况 解决方法...

详解Python中的__getitem__方法与slice对象的切片操作

Fib实例虽然能作用于for循环,看起来和list有点像,但是,把它当成list来使用还是不行,比如,取第5个元素: >>> Fib()[5] Traceback...

通过python下载FTP上的文件夹的实现代码

复制代码 代码如下:# -*- encoding: utf8 -*-import osimport sysimport ftplibclass FTPSync(object): ...