鱼C论坛

 找回密码
 立即注册
查看: 626|回复: 0

[技术交流] Python bytes() 函数

[复制链接]
发表于 2020-3-20 20:17:24 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 一个账号 于 2020-3-20 20:48 编辑

Python bytes() 函数


语法

  1. bytes([source[, encoding[, errors]]])
复制代码

  1. bytes(iterable_of_ints) -> bytes
  2. bytes(string, encoding[, errors]) -> bytes
  3. bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
  4. bytes(int) -> bytes object of size given by the parameter initialized with nullbytes
  5. bytes() -> empty bytes object
复制代码


参数

参数描述
encoding指定字符串的编码格式,当 source 为字符串时,必选
errors这个参数一般不需要设置,默认是 "strict"。还有其他选项,比如 "ignore"


source

1. 如果参数是一个字符串,你必须设置 encoding 参数来指定的它的编码格式。

2. 如果参数是一个整数,将会按照整数的数值,使用对应数量的空字节(\x00)来表示。

3. 如果参数为与 buffer 接口一致的对象,则从一个字节序列或者 buffer 复制出一个不可变的 bytearray 对象。

4. 如果参数是可迭代的,则它的每一个值都必须是 0~255 的整数,它们将被用作数组的初始化值。

5. 如果参数未设置或者值为空,则会返回一个空值。

返回值

返回一个不可变的字节数组。

例子

  1. >>> bytes()
  2. b''
  3. >>> bytes([])
  4. b''
  5. >>> bytes(0)
  6. b''
  7. >>> bytes("abc", "gbk")
  8. b'abc'
  9. >>> bytes(3)
  10. b'\x00\x00\x00'
  11. >>> bytes(5)
  12. b'\x00\x00\x00\x00\x00'
  13. >>> bytes(range(6))
  14. b'\x00\x01\x02\x03\x04\x05'
  15. >>> bytes([1, 2, 3, 4])
  16. b'\x01\x02\x03\x04'
  17. >>> bytes([1, 2, 3, 256])   # 元素不能大于 255
  18. Traceback (most recent call last):
  19.   File "<pyshell#11>", line 1, in <module>
  20.     bytes([1, 2, 3, 256])
  21. ValueError: bytes must be in range(0, 256)
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-14 21:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表