第3条了解bytes、str和unicode的区别

Vevina ·
更新时间:2024-09-20
· 754 次阅读

1.Python3的字符类型

Python3中有两种表示字符序列的类型:

str:包含Unicode字符 bytes:包含原始8位

而Python2也有两种表示字符序列的类型:

str:包含原始8位 unicode:代表Unicode编码

需要注意的是,Python2和Python3的Unicode和str实例都没有和特定的二进制编码相关联,因此想要把Unicode字符转换成二进制数据,必须使用encode方法,而将二进制转换成Unicode需要使用decode方法。

Python3的文件读取方式

Python3中open()函数含有encoding参数,默认值’utf-8’

以二进制写入(wb)模式打开文件 import os with open('/ex/test.bin','wb') as f: f.write(os.urandom(10)) 读取文件以rb模式读取 import os with open('/ex/test.bin','rb') as f: f.read() 总结 Python3中,bytes是一种包含8位的序列,str是一个包含Unicode字符的序列。 从文件读取二进制文件时,或者向其中写入二进制数据时,必须指定’wb’或者‘rb’模式。
作者:竹石破岩



str bytes unicode

需要 登录 后方可回复, 如果你还没有账号请 注册新账号