打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
(ok)Python3编码问题 Unicode utf

为什么需要本文,因为在对接某些很老的接口的时候,需要传递过去的是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())  #直接输出为普通字符串
  • /////////////////////////////////////

  • #英文使用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())  #直接输出为普通字符串


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
第15关笔记
python中的编码问题:以ascii和unicode为主线
Defining Python Source Code Encodings
字符串加密之后在解密
python2和3编码
Python2到Python3的奇葩字符串问题,小心踩坑哦
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服