Python3中的bytes和str类型详解


Posted in Python onMay 02, 2019

Python 3最重要的新特性之一是对字符串和二进制数据流做了明确的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式混用str和bytes,你不能拼接字符串和字节流,也无法在字节流里搜索字符串(反之亦然),也不能将字符串传入参数为字节流的函数(反之亦然)。

下面让我们深入分析一下二者的区别和联系。

编码发展的历史

在谈bytes和str之前,需要先说说关于编码是如何发展的。。

在计算机历史的早期,美国为代表的英语系国家主导了整个计算机行业,26个英文字母组成了多样的英语单词、语句、文章。因此,最早的字符编码规范是ASCII码,一种8位即1个字节的编码规范,它可以涵盖整个英语系的编码需要。

编码是什么?编码就是把一个字符用一个二进制来表示。我们都知道,所有的东西,不管是英文、中文还是符号等等,最终存储在磁盘上都是01010101这类东西。在计算机内部,读取和存储数据归根结底,处理的都是0和1组成的比特流。问题来了,人类看不懂这些比特流,如何让这些010101对人类变得可读呢?于是出现了字符编码,它是个翻译机,在计算机内部某个地方,透明的帮我们将比特流翻译成人类可以直接理解的文字。对于一般用户,不需要知道这个过程是什么原理,是怎么执行的。但是对于程序员却是个必须搞清楚的问题。

以ASCII编码为例,它规定1个字节8个比特位代表1个字符的编码,也就是“00000000”这么宽,一个一个字节的解读。例如:01000001表示大写字母A,有时我们会“偷懒"的用65这个十进制来表示A在ASCII中的编码。8个比特位,可以没有重复的最多表示2的8次方(255)个字符。

后来,计算机得到普及,中文、日文、韩文等等国家的文字需要在计算机内表示,ASCII的255位远远不够,于是标准组织制定出了叫做UNICODE的万国码,它规定任何一个字符(不管哪国的)至少以2个字节表示,可以更多。其中,英文字母就是用2个字节,而汉字是3个字节。这个编码虽然很好,满足了所有人的要求,但是它不兼容ASCII,同时还占用较多的空间和内存。因为,在计算机世界更多的字符是英文字母,明明可以1个字节就能够表示,非要用2个。

于是UTF-8编码应运而生,它规定英文字母系列用1个字节表示,汉字用3个字节表示等等。因此,它兼容ASCII,可以解码早期的文档。UTF-8很快就得到了广泛的应用。

在编码的发展历程中,我国还创造了自己的编码方式,例如GBK,GB2312,BIG5。他们只局限于在国内使用,不被国外认可。在GBK编码中,中文汉字占2个字节。

bytes和str之间的异同

回到bytes和str的身上。bytes是一种比特流,它的存在形式是01010001110这种。我们无论是在写代码,还是阅读文章的过程中,肯定不会有人直接阅读这种比特流,它必须有一个编码方式,使得它变成有意义的比特流,而不是一堆晦涩难懂的01组合。因为编码方式的不同,对这个比特流的解读也会不同,对实际使用造成了很大的困扰。下面让我们看看Python是如何处理这一系列编码问题的:

>>> s = "中文"
>>> s
'中文'
>>> type(s)
<class 'str'>
>>> b = bytes(s, encoding='utf-8')
>>> b
b'\xe4\xb8\xad\xe6\x96\x87'   #\x 代表是十六进制
>>> type(b)
<class 'bytes'>

从例子可以看出,s是个字符串类型。Python有个内置函数bytes()可以将字符串str类型转换成bytes类型,b实际上是一串01的组合,但为了在ide环境中让我们相对直观的观察,它被表现成了b'\xe4\xb8\xad\xe6\x96\x87'这种形式,开头的b表示这是一个bytes类型。\xe4是十六进制的表示方式,它占用1个字节的长度,因此”中文“被编码成utf-8后,我们可以数得出一共用了6个字节,每个汉字占用3个,这印证了上面的论述。在使用内置函数bytes()的时候,必须明确encoding的参数,不可省略。

我们都知道,字符串类str里有一个encode()方法,它是从字符串向比特流的编码过程。而bytes类型恰好有个decode()方法,它是从比特流向字符串解码的过程。除此之外,我们查看Python源码会发现bytes和str拥有几乎一模一样的方法列表,最大的区别就是encode和decode。

从实质上来说,字符串在磁盘上的保存形式也是01的组合,也需要编码解码。

如果,上面的阐述还不能让你搞清楚两者的区别,那么记住下面两几句话:

在将字符串存入磁盘和从磁盘读取字符串的过程中,Python自动地帮你完成了编码和解码的工作,你不需要关心它的过程。

使用bytes类型,实质上是告诉Python,不需要它帮你自动地完成编码和解码的工作,而是用户自己手动进行,并指定编码格式。

Python已经严格区分了bytes和str两种数据类型,你不能在需要bytes类型参数的时候使用str参数,反之亦然。这点在读写磁盘文件时容易碰到。

在bytes和str的互相转换过程中,实际就是编码解码的过程,必须显式地指定编码格式。

>>> b
b'\xe4\xb8\xad\xe6\x96\x87'
>>> type(b)
<class 'bytes'>
>>> s1 = str(b)
>>> s1
"b'\\xe4\\xb8\\xad\\xe6\\x96\\x87'"  #注意这里
>>> type(s1)
<class 'str'>
>>> s1 = str(b, encoding='utf-8')
>>> s1
'中文'
>>> type(s1)
<class 'str'>

我们再把字符串s1,转换成gbk编码的bytes类型:

>>> s1
'中文'
>>> type(s1)
<class 'str'>
>>> b = bytes(s1, encoding='gbk')
>>> b

编码可以将抽象字符以二进制数据的形式表示,有很多编码方法,如utf-8、gbk等,可以使用encode()函数对字符串进行编码,转换成二进制字节数据,也可用decode()函数将字节解码成字符串;用decode()函数解码,可不要用指定编码格式;

>>> a = 'hello world'
>>> type(a)
<class 'str'>
>>> a
'hello world'

a. 按utf-8的方式编码,转成bytes:以及解码成字符串

#a为串'hello world'
>>> b = a.encode(encoding='utf-8')
>>> type(b)
<class 'bytes'>
>>>
>>> b
b'hello world'
>>>
>>>
>>> c = b.decode(encoding='utf-8')
>>> type(c)
<class 'str'>
>>> c
'hello world'

b. 按gbk的方式编码,转成bytes:以及解码成字符串

path="doc.txt"
 
f=open(path,'rb')
 
raw=f.read()
print(raw[:100])
print(len(raw))
print(type(raw))
 
raw1=str(raw)
print(raw1[:100])
print(len(raw1))
print(type(raw1))
 
tokens=word_tokenize(raw1)
print(len(tokens))
print(tokens[:20])
b'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash eve'
626168
<class 'bytes'>
b'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash
634857
<class 'str'>
115104
["b'the", 'rock', 'is', 'destined', 'to', 'be', 'the', '21st', 'century\\', "'s", 'new', '``', 'conan', '``', 'and', 'that', 'he\\', "'s", 'going', 'to']
from nltk import word_tokenize
 
path="doc.txt" 
 
f=open(path,'rb') 
 
raw=f.read() 
print(raw[:1000]) 
print(len(raw)) 
print(type(raw)) 
raw=raw[:1000]
 
 
raw1= raw.decode(encoding='utf-8') #在4000多的位置上有无法解码的,也就是说解码方式是有问题的,应该不是utf-8
print(raw1[:1000]) 
print(len(raw1)) 
print(type(raw1))
b'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal . \nthe gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth . \neffective but too-tepid biopic\nif you sometimes like to go to the movies to have fun , wasabi is a good place to start . \nemerges as something rare , an issue movie that\'s so honest and keenly observed that it doesn\'t feel like one . \nthe film provides some great insight into the neurotic mindset of all comics -- even those who have reached the absolute top of the game . \noffers that rare combination of entertainment and education . \nperhaps no picture ever made has more literally showed that the road to hell is paved with good intentions . \nsteers turns in a snappy screenplay that curl'
626168
<class 'bytes'>
the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal . 
the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson's expanded vision of j . r . r . tolkien's middle-earth . 
effective but too-tepid biopic
if you sometimes like to go to the movies to have fun , wasabi is a good place to start . 
emerges as something rare , an issue movie that's so honest and keenly observed that it doesn't feel like one . 
the film provides some great insight into the neurotic mindset of all comics -- even those who have reached the absolute top of the game . 
offers that rare combination of entertainment and education . 
perhaps no picture ever made has more literally showed that the road to hell is paved with good intentions . 
steers turns in a snappy screenplay that curl
1000
<class 'str'>

189
['e', 'rock', 'is', 'destined', 'to', 'be', 'the', '21st', 'century', "'s", 'new', '``', 'conan', '``', 'and', 'that', 'he', "'s", 'going', 'to']

将a(字符串)进行编码,当a为中文时,将Unicode编码为b'\\u4f60\\u597d',输入b显示时,python自动假设unicode字符的默认编码方式是ASCII,但ASCII中没有b'\\u4f60\\u597d',所以就直接输出了。

当a为'hello'时,编码为(也是数字),但print时可以按照ASCII的形式显示bytes类型。

>>>a='你好'
>>>b=a.encode('unicode_escape')
>>>b
b'\\u4f60\\u597d'
 
 
>>>a='hello'
>>>b=a.encode('unicode_escape')
>>>b
b'hello'

以上所述是小编给大家介绍的Python3中的bytes和str类型详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
小结Python用fork来创建子进程注意事项
Jul 03 Python
python基础教程之对象和类的实际运用
Aug 29 Python
Python通过poll实现异步IO的方法
Jun 04 Python
python3实现抓取网页资源的 N 种方法
May 02 Python
计算机二级python学习教程(2) python语言基本语法元素
May 16 Python
pyenv与virtualenv安装实现python多版本多项目管理
Aug 17 Python
树莓派极简安装OpenCv的方法步骤
Oct 10 Python
MxNet预训练模型到Pytorch模型的转换方式
May 25 Python
什么是python的id函数
Jun 11 Python
Python unittest生成测试报告过程解析
Sep 08 Python
浅谈Python __init__.py的作用
Oct 28 Python
Python通过m3u8文件下载合并ts视频的操作
Apr 16 Python
利用pyinstaller打包exe文件的基本教程
May 02 #Python
Python中psutil的介绍与用法
May 02 #Python
Python3.5字符串常用操作实例详解
May 01 #Python
Python3.5文件修改操作实例分析
May 01 #Python
详解pandas的外部数据导入与常用方法
May 01 #Python
Python3.5文件读与写操作经典实例详解
May 01 #Python
Python3.5集合及其常见运算实例详解
May 01 #Python
You might like
超级兔子让浮动层消失的前因后果
2007/03/09 Javascript
获得所有表单值的JQuery实现代码[IE暂不支持]
2012/05/24 Javascript
jquery+ajax+C#实现无刷新操作数据库数据的简单实例
2014/02/08 Javascript
在JavaScript中操作时间之getUTCDate()方法的使用
2015/06/10 Javascript
js判断浏览器是否支持严格模式的方法
2016/10/04 Javascript
从零开始学习Node.js系列教程一:http get和post用法分析
2017/04/13 Javascript
详解微信小程序 template添加绑定事件
2017/06/23 Javascript
实现div内部滚动条滚动到底部和顶部的代码
2017/11/15 Javascript
微信小程序实现动态改变view标签宽度和高度的方法【附demo源码下载】
2017/12/05 Javascript
AngularJS 将再发布一个重要版本 然后进入长期支持阶段
2018/01/31 Javascript
微信小程序自定义底部弹出框
2020/11/16 Javascript
vue this.reload 方法 配置
2018/09/12 Javascript
[30:55]完美世界DOTA2联赛PWL S2 Magma vs LBZS 第二场 11.18
2020/11/18 DOTA
Python进程间通信用法实例
2015/06/04 Python
Python通过90行代码搭建一个音乐搜索工具
2015/07/29 Python
通过Python来使用七牛云存储的方法详解
2015/08/07 Python
Tensorflow 同时载入多个模型的实例讲解
2018/07/27 Python
Pandas的read_csv函数参数分析详解
2019/07/02 Python
python使用正则来处理各种匹配问题
2019/12/22 Python
使用Python制作缩放自如的圣诞老人(圣诞树)
2019/12/25 Python
深度学习入门之Pytorch 数据增强的实现
2020/02/26 Python
Python如何存储数据到json文件
2020/03/09 Python
使用python创建Excel工作簿及工作表过程图解
2020/05/27 Python
python3.6.5基于kerberos认证的hive和hdfs连接调用方式
2020/06/06 Python
Python轻量级web框架bottle使用方法解析
2020/06/13 Python
Python Selenium模块安装使用教程详解
2020/07/09 Python
网页中的电话号码如何实现一键直呼效果_附示例
2016/03/15 HTML / CSS
HTML5 图片预加载的示例代码
2020/03/25 HTML / CSS
党员创先争优公开承诺书
2014/03/28 职场文书
音乐幼师求职信
2014/07/09 职场文书
基层党员群众路线教育实践活动个人对照检查材料思想汇报
2014/10/05 职场文书
2014年个人技术工作总结
2014/12/08 职场文书
优秀教师先进材料
2014/12/16 职场文书
2014年学生管理工作总结
2014/12/20 职场文书
趣味运动会新闻稿
2015/07/17 职场文书
mysql中整数数据类型tinyint详解
2021/12/06 MySQL