python的字节串
python的字节串
本文环境为python3.7
认识字节串
字节串,也叫字节序列(bytes),用来存储以字节为单位的数据。
创建空的字节串
>>> string=b''
>>> type(string)
<class 'bytes'>
>>> string=b""
>>> type(string)
<class 'bytes'>
可以看到string的类型为bytes
创建非空的字节串
>>> string1=b'hello world'
>>> type(string1)
<class 'bytes'>
>>> string2=b'\x62\x71'
>>> type(string2)
<class 'bytes'>
可以看到字节串的典型特征为 b'this is a bytes'
,以b为前缀。
字节串与字符串的相互转化
string1 = "hello world" # this is str
string2 = b"hello world" # this is bytes
print('change str into bytes')
print(bytes(string1, encoding='utf-8'))
print(str.encode(string1)) # 默认编码方式就是utf-8
print(string1.encode('utf-8')) # 默认编码方式就是utf-8,可以直接写成string1.encode()
print('--------------')
print('change bytes into str')
print(str(string2, encoding='utf-8'))
print(bytes.decode(string2)) # 默认解码方式就是utf-8
print(string2.decode('utf-8')) # 默认解码方式就是utf-8,可以直接写成string2.decode()
运行结果:
change str into bytes
b'hello world'
b'hello world'
b'hello world'
--------------
change bytes into str
hello world
hello world
hello world
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类