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
posted @   jackie_le  阅读(591)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示