Python bytes() 函数
本帖最后由 一个账号 于 2020-3-20 20:48 编辑Python bytes() 函数
语法
bytes(]])
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with nullbytes
bytes() -> empty bytes object
参数
参数描述
encoding指定字符串的编码格式,当 source 为字符串时,必选
errors这个参数一般不需要设置,默认是 "strict"。还有其他选项,比如 "ignore"
source
1. 如果参数是一个字符串,你必须设置 encoding 参数来指定的它的编码格式。
2. 如果参数是一个整数,将会按照整数的数值,使用对应数量的空字节(\x00)来表示。
3. 如果参数为与 buffer 接口一致的对象,则从一个字节序列或者 buffer 复制出一个不可变的 bytearray 对象。
4. 如果参数是可迭代的,则它的每一个值都必须是 0~255 的整数,它们将被用作数组的初始化值。
5. 如果参数未设置或者值为空,则会返回一个空值。
返回值
返回一个不可变的字节数组。
例子
>>> bytes()
b''
>>> bytes([])
b''
>>> bytes(0)
b''
>>> bytes("abc", "gbk")
b'abc'
>>> bytes(3)
b'\x00\x00\x00'
>>> bytes(5)
b'\x00\x00\x00\x00\x00'
>>> bytes(range(6))
b'\x00\x01\x02\x03\x04\x05'
>>> bytes()
b'\x01\x02\x03\x04'
>>> bytes() # 元素不能大于 255
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
bytes()
ValueError: bytes must be in range(0, 256)
页:
[1]