Python bytes()
时间:2020-02-23 14:42:29 来源:igfitidea点击:
Python bytes()是一个内置函数。
此函数返回字节对象,该对象是不可变的整数序列,范围为0 <= x <256。
Python bytes()
Python bytes()函数语法为:
class bytes(]])
source用于初始化bytes对象。
这是一个可选参数。
除非源是字符串,否则" encoding"是可选的。
使用str.encode()
函数将字符串转换为字节。
错误是可选参数。
如果来源是字符串,并且由于某些错误导致编码失败,则使用此格式。
根据源类型,有一些特定的规则,后跟bytes()函数。
如果未传递任何参数,则返回空字节对象。
如果source是整数,它将使用给定长度的数组(其值为空)初始化bytes对象。
如果源是字符串,则编码是强制性的,用于将字符串转换为字节数组。
如果source是可迭代的(例如list),则它必须是0 <= x <256范围内的整数的可迭代对象,这些整数用作数组的初始内容。
总体而言,bytes()函数与bytearray()函数非常相似。
我们来看一些bytes()函数的示例。
没有参数的bytes()
b = bytes() print(b)
输出:b'
具有字符串和不变性的bytes()
# string to bytes # encoding is mandatory, otherwise "TypeError: string argument without an encoding" b = bytes('abc', 'UTF-8') print(b) # Below code will throw error: # TypeError: 'bytes' object does not support item assignment # b[1] = 65 # immutable
输出:b'abc'
请注意,如果尝试更改bytes对象中的元素值,则会收到一条错误消息,如上面的注释所示。
具有int参数的bytes()
# bytes of given size, elements initialized to null b = bytes(5) print(b)
输出:'b'\ x00 \ x00 \ x00 \ x00 \ x00'
具有可迭代的bytes()
# bytes from iterable b = bytes([1, 2, 3]) print(b)
输出:'b'\ x01 \ x02 \ x03'