python utf-8/gbk/unicode 编码及解码
如果想知道python 的某个bytes类型是通过什么类型编码,可以先安装chardet 。
1 | pip install chardet |
Python utf-8 编码及解码
1 2 3 4 5 6 7 | str = "python编码" # 转为utf-8 类型的bytes 字符串 str_utf8 = str.encode( "utf-8" ) print( "转码结果:" +repr(str_utf8)) print(type(str_utf8)) print(chardet.detect(str_utf8)) print( "解码结果:" +str_utf8.decode( "utf-8" )) |
运行结果:
1 2 3 4 5 | 转码结果:b 'python\xe7\xbc\x96\xe7\xa0\x81' < class 'bytes' > { 'encoding' : 'utf-8' , 'confidence' : 0.7525, 'language' : '' } 解码结果:python编码 转码结果:b 'python\xb1\xe0\xc2\xeb' |
Python gbk 编码及解码
1 2 3 4 5 6 | # 转为gbk 类型的bytes 字符串 str_gbk = str.encode( "gbk" ) print( "转码结果:" +repr(str_gbk)) print(type(str_gbk)) print(chardet.detect(str_gbk)) print( "解码结果:" +str_gbk.decode( "gbk" )) |
运行结果:
转码结果:b'python\xb1\xe0\xc2\xeb' <class 'bytes'> {'encoding': None, 'confidence': 0.0, 'language': None} 解码结果:python编码
Python unicode 编码及解码
1 2 3 4 5 6 | # 转为unicode 类型的bytes 字符串 str_unicode = str.encode( "unicode-escape" ) print( "转码结果:" +repr(str_unicode)) print(type(str_unicode)) print(chardet.detect(str_unicode)) print( "解码结果:" +str_unicode.decode( "unicode-escape" )) |
运行结果:
1 2 3 4 | 转码结果:b 'python\\u7f16\\u7801' < class 'bytes' > { 'encoding' : 'ascii' , 'confidence' : 1.0, 'language' : '' } 解码结果:python编码 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端