约 2039 字

约 10 分钟

#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

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#推荐阅读

更新: 2025/10/25

作者: PlanC

创建: 2025/6/9