str和bytes什么区别,两者的转换是怎样
Admin 2022-09-14 群英技术资讯 802 次浏览
这篇文章我们来了解“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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
函数代码块以def关键词开头,后接函数标识符名称和圆括号(),任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数,函数的第一行语句可以选择性地使用文档字符串,函数内容以冒号起始,并且缩进。
这篇文章主要为大家介绍了python神经网络InceptionV3模型复现详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪<BR>
常规版本简单的for循环遍历x_n=["x1","x2","x3"]forxinx_n:print(x)>>x1x2x3借助range()和len()x_n=["x1","x2","x3"]foriinrange(len(x_n)):print(...
Python由荷兰数学和计算机科学研究学会 于1990 年代初设计,作为一门叫做ABC语言的替代品。Python语法和动态类型,以及解释型语言的本质,使它成为多数平台上写脚本和快速开发应用的编程语言
怎样用Python实现文本的滚动播放?对于文本滚动播放的应用场景有很多,我们经常能在网站的顶部看到,文本滚动播放功能也是比较实用的,下面我们就来看看用Python怎样写文本的滚动播放功能。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008