str和bytes什么区别,两者的转换是怎样
Admin 2022-09-14 群英技术资讯 572 次浏览
这篇文章我们来了解“str和bytes什么区别,两者的转换是怎样”的内容,小编通过实际的案例向大家展示了操作过程,简单易懂,有需要的朋友可以参考了解看看,那么接下来就跟随小编的思路来往下学习吧,希望对大家学习或工作能有帮助。
在Python3中,字符序列有两种类型:bytes和str。bytes类型是无符号的8位值(通常以ASCII码显式),而str类型是Unicode代码点(code point)。代码点指编码字符集中,字符所对应的数字。
a = b'hello world' print(isinstance(a, bytes)) print(list(a)) print(a) """ True [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] b'hello world' """ a = 'hello world' print(isinstance(a, str)) print(list(a)) print(a) """ True ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] hello world """
isinstance()方法可以判断对象的类型,例如这里用来判断是str还是bytes。
Python3对文本(str)和二进制数据(bytes)有着严格的区分,不能混用。
x = b'python' y = b'java' z = 'c++' w = 'c' print(x + y) # b'pythonjava' print(z + w) # c++c print(x + z) # TypeError: can't concat str to bytes print('python' == b'python') # False
上述示例中str类型和bytes类型间使用=来比较是否相等不会报错,但是会返回False。
str类型和bytes类型间可以相互转换。
str到bytes的转换需要调用encode()方法。
bytes到str间的转换需要调用decode()方法。
x = b'python' y = x.decode(encoding='utf-8') z = y.encode(encoding='utf-8') print(y) print(z) """ python b'python' """
可以观察到encode()和decode()方法都有一个encoding参数用来指定具体的编码规则。
当要将bytes类型写入到文件中时,必须指定mode=wb。读取二进制文件时可以指定mode=rb或者指定编码方式,使用后者时读出来的就不是bytes类型的字符序列了。
x = b'python' # 错误示例 with open('data.bin', mode='w') as fp: fp.write(x) # TypeError: write() argument must be str, not bytes # 正确示例 with open('data.bin', mode='wb') as fp: fp.write(x) # 读取二进制文件方式1 with open('data.bin', mode='rb') as fp: content = fp.read() print(content) # python # 读取二进制文件方式2 with open('data.bin', mode='r', encoding='utf-8') as fp: content = fp.read() print(content, type(content)) # python <class 'str'>
当读写Unicode数据时,只需要注意下编码方式即可,最好是显式的传递encoding参数。
x = '世界你好' with open('data.txt', mode='w', encoding='utf-8') as fp: fp.write(x) with open('data.txt', mode='r', encoding='utf-8') as fp: content = fp.read() print(content) # 世界你好 # 错误示例,编码方式不对 with open('data.txt', mode='r', encoding='gbk') as fp: content = fp.read() print(content) # 涓栫晫浣犲ソ
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
本篇文章给大家详细分析了Python的优点和缺点以及相关的优势劣势分析,对此有兴趣的朋友学习下。
python fire是什么?就是以广义对象的方式玩命令行,可以是类、函数、字典、列表等,更灵活简单。
一、概述random模块用于生成伪随机数之所以称之为伪随机数,是因为真正意义上的随机数(或者随机事件)在某次产生过程中是按照实验过程中表
这篇文章给大家分享如何用python实现验证密码三次的效果的代码,小编觉得挺实用的,验证码验证在很多登录业务都会使用到,因此分享给大家做个参考,接下来一起跟随小编看看吧。
这篇文章给大家分享的是Python的flask框架中转换器的使用,下文介绍了默认转换器和自定义转换器的使用,对大家会有一定的参考价值,有需要的朋友可以了解看看,接下来就跟随小编一起学习一下吧。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008