#Python 的内置函数 bytes
说明:类型转换为 bytes。
bytes
是不可变的字节数组;与之相对,bytearray 是可变的字节数组。
#函数说明
class bytes(x=b''):
'''
创建 bytes
:param x: 要转换的变量
:return: x 转换为 bytes 后的值
'''
说明
将变量转换为 bytes
类型。
参数
x
- 要转换为bytes
的变量,默认为b''
,即创建一个空的bytes
- 类型为
bytes
时拷贝该内容创建一个新的bytes
- 类型为
int
时创建一个长度为x
元素值全部为 0 的bytes
- 类型为
返回值
转换为 bytes
后的值。
class bytes(x, encoding):
'''
创建 bytes
:param x: 要转换的变量
:param encoding: 编码
:return: x 转换为 bytes 后的值
'''
说明
将变量转换为 bytes
类型。
参数
x
- 要转换为bytes
的变量,通常是str
encoding
- 转换时使用的编码
返回值
转换为 bytes
后的值。
class bytes(x, encoding, errors):
'''
创建 bytes
:param x: 要转换的变量
:param encoding: 编码
:param errors: 编码错误的处理方式
:return: x 转换为 bytes 后的值
'''
说明
将变量转换为 bytes
类型。
参数
x
- 要转换为bytes
的变量,通常是str
encoding
- 转换时使用的编码errors
- 编码错误的处理方式
返回值
转换为 bytes
后的值。
#编码错误的处理方式
None
或'strict'
- 编码错误时产生ValueError
异常'ignore'
- 忽略错误,通常会丢失数据'replace'
- 使用'?'
替换有错误的位置'surrogateescape'
- 使用U+DC08
至U+DCFF
之间的值表示不正确的字节'xmlcharrefreplace'
- 编码格式不支持的字符将被替换为相应的 XML 字符引用,仅在写入时可用'backslashreplace'
- 使用反斜杠转义表示错误的数据'namereplace'
- 使用\N{...}
转义表示错误的数据
#示例
print(b'abcd') # 拷贝该另一个 bytes
print(bytes(10)) # 长度为 10,元素全部为 0
print(bytes('hello', encoding='utf-8')) # 将字符串编码为 bytes