目录
bytes-不可变的字节序列
表示 bytes 字面值的语法与字符串字面值的大致相同,只是添加了一个 b
前缀:
-
单引号:
b'允许嵌入 "双" 引号'
。 -
双引号:
b"允许嵌入 '单' 引号"
。 -
三重引号:
b'''三重单引号'''
,b"""三重双引号"""
创建与赋值
>>> bt = b'\x01\x00\x00\x08'
>>> bt
b'\x01\x00\x00\x08'
操作符
访问(序列操作符切片)
想来在看本文之前,你已经看了python-字符串总结,切片应该已经会了,不再重复理论,直接演示。
>=0时的index | 0 | 1 | 2 | 3 |
---|---|---|---|---|
bytes(十六进制) | 01 | 00 | 00 | 08 |
<0时的index | -4 | -3 | -2 | -1 |
>>> bt[0]
1
>>> bt[0:3]
b'\x01\x00\x00'
>>> bt[0:4:2]
b'\x01\x00'
>>> bt[::-1]
b'\x08\x00\x00\x01'
判断子序列(成员操作符in、not in)
>>> b'\x00' in bt
True
>>> b'\x01' not in bt
False
拼接(操作符+)
>>> bt + b'\xff'
b'\x01\x00\x00\x08\xff'
重复(操作符*)
>>> bt * 2
b'\x01\x00\x00\x08\x01\x00\x00\x08'
比较(操作符==、!=、<、=<、>、>=)
>>> bt == bt
True
>>> bt != bt
False
>>> bt < bt[0:3] + b'\x10'
True
>>> bt <= bt
True
>>> bt > bt
False
>>> bt >= bt[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'bytes' and 'int'
>>> bt >= bt[0:2]
True
注意,bytes类型使用切片为一个时,类型会变为int,需要转换。
>>> type(bt[3])
<class 'int'>>>> bt >= bytes(bt[0])
True
删除
关键字del, del 变量名
>>> del bt
>>> bt
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bt' is not defined
方法
对比一下字符串(删除了__*__)。
>>> dir(str)
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir(bytes)
[ 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'hex', 'index', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
方法与字符串类似,只不过参数变为了字节
>>> b'lady_killer9'.replace(b'l',b'L')
b'Lady_kiLLer9'
其余常见方法可查看Python-字符串总结(创建、操作符、方法、相关内置函数、相关模块),接下来展示不一样的。
十六进制
fromhex(str)
此bytes类方法返回一个解码给定字符串的 bytes 对象。 字符串必须由表示每个字节的两个十六进制数码构成,其中的 ASCII 空白符会被忽略。
hex()
返回一个字符串对象,该对象包含实例中每个字节的两个十六进制数字。
>>> bt = bytes.fromhex('01000008')
>>> bt
b'\x01\x00\x00\x08'
>>> bt.hex()
'01000008'
解码
decode(self, /, encoding='utf-8', errors='strict')
>>> bt.decode(encoding='ascii')
'\x01\x00\x00\x08'
内置函数
class bytes
([source[, encoding[, errors]]])
bytes 字面值中只允许 ASCII 字符(无论源代码声明的编码为何)。 任何超出 127 的二进制值必须使用相应的转义序列形式加入 bytes 字面值。像字符串字面值一样,bytes 字面值也可以使用 r
前缀来禁用转义序列处理。
虽然 bytes 字面值和表示法是基于 ASCII 文本的,但 bytes 对象的行为实际上更像是不可变的整数序列,序列中的每个值的大小被限制为 0 <= x < 256
(如果违反此限制将引发ValueError)。
除了字面值形式,bytes 对象还可以通过其他几种方式来创建:
-
指定长度的以零值填充的 bytes 对象:
bytes(10)
-
通过由整数组成的可迭代对象:
bytes(range(20))
-
通过缓冲区协议复制现有的二进制数据:
bytes(obj)
模块
struct
将字节串解读为打包的二进制数据,读过一些协议相关的部分代码,里面就有这个。
bytearray-可变的字节序列
创建
class bytearray
([source[, encoding[, errors]]])
bytearray 对象没有专属的字面值语法,它们总是通过调用构造器来创建:
-
创建一个空实例:
bytearray()
-
创建一个指定长度的以零值填充的实例:
bytearray(10)
-
通过由整数组成的可迭代对象:
bytearray(range(20))
-
通过缓冲区协议复制现有的二进制数据:
bytearray(b'Hi!')
由于 bytearray 对象是可变的,还支持序列操作。与byte相同的不再重复。
方法
>>> dir(bytes)
[ 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'hex', 'index', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir(bytearray)
['append', 'capitalize', 'center', 'clear', 'copy', 'count', 'decode', 'endswith', 'expandtabs', 'extend', 'find', 'fromhex', 'hex', 'index', 'insert', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'pop', 'remove', 'replace', 'reverse', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
添加
append(item)
在后面添加一个对象(整数),非整数时TypeError。
>>> bt = b'01000008'
>>> bta = bytearray(bt)
>>> bta
bytearray(b'01000008')
>>> bta.append('lady_killer9')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> bta.append(30)
>>> bta
bytearray(b'01000008\x1e')
extend(iterable_of_ints)
将一个全是int的可迭代对象依次添加到后面,可能效率比for循环+append要高,不然官方应该也不会加。
>>> bte = bytearray()
>>> lst = [i for i in range(65,75)]
>>> bte.extend(lst)
>>> bte
bytearray(b'ABCDEFGHIJ')
复制
copy()
返回一个拷贝后的bytearray对象,id不同。
>>> id(bta)
1829219244656
>>> bta_copy = bta.copy()
>>> bta_copy
bytearray(b'01000008\x1e')
>>> id(bta_copy)
1829219048752
删除
pop(index=-1)。
index是索引,会删除的那个字节,默认-1即最后一个字节。
返回删除的那个字节对应的整数。
>>> bta.pop()
30
>>> bta
bytearray(b'01000008')
>>> bta.append(65)
>>> bta
bytearray(b'01000008A')
remove(value)
仅删除第一个ascii码等于value的值,value为十进制,未找到时ValueError。
>>> bta.remove(00)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: value not found in bytearray
>>> bta.remove(48)
>>> bta
bytearray(b'1000008A')
>>> bta.remove(48)
>>> bta
bytearray(b'100008A')>>> list(bta)
[49, 48, 48, 48, 48, 56, 65]
clear()
清空bytearray
>>> bta.clear()
>>> bta
bytearray(b'')
总结
bytes相比str,增加了一些方法,其余的查看查看Python-字符串总结(创建、操作符、方法、相关内置函数、相关模块)。
bytesarray相比bytes增加了一些列表的类似方法,可查看Python-列表总结(操作符、方法、内置函数、相关模块)。
更多python相关内容:【python总结】python学习框架梳理
本人b站账号:lady_killer9
有问题请下方评论,转载请注明出处,并附有原文链接,谢谢!如有侵权,请及时联系。如果您感觉有所收获,自愿打赏,可选择支付宝18833895206(小于),您的支持是我不断更新的动力。