python utf-8/gbk/unicode 编码及解码

2022/7/11 14:20:53

本文主要是介绍python utf-8/gbk/unicode 编码及解码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

如果想知道python 的某个bytes类型是通过什么类型编码,可以先安装chardet 。

pip install chardet

 

 Python utf-8 编码及解码

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"))

运行结果:

转码结果: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 编码及解码

# 转为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 编码及解码

# 转为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"))

运行结果:

转码结果:b'python\\u7f16\\u7801'
<class 'bytes'>
{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
解码结果:python编码

 



这篇关于python utf-8/gbk/unicode 编码及解码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程