📜  Python bytes()

📅  最后修改于: 2020-09-20 03:51:52             🧑  作者: Mango

bytes()方法返回一个不可变的字节对象,该对象使用给定的大小和数据初始化。

bytes()方法的语法为:

bytes([source[, encoding[, errors]]])

bytes()方法返回一个bytes对象,该对象是一个范围为0 <=x < 256的整数(不可修改)。

如果要使用可变版本,请使用bytearray()方法。

bytes()参数

bytes()具有三个可选参数:

  1. source(可选)-用于初始化字节数组的source。
  2. 编码(可选) -如果源是一个字符串,该字符串的编码。
  3. 错误(可选)-如果源是字符串,则在编码转换失败时采取的措施(更多信息:字符串编码)

可以通过以下方式使用source参数初始化字节数组:

Different source parameters
Type Description
String Converts the string to bytes using str.encode() Must also provide encoding and optionally errors
Integer Creates an array of provided size, all initialized to null
Object A read-only buffer of the object will be used to initialize the byte array
Iterable Creates an array of size equal to the iterable count and initialized to the iterable elements Must be iterable of integers between 0 <= x < 256
No source (arguments) Creates an array of size 0

从bytes()返回值

bytes()方法返回给定大小和初始化值的bytes对象。

示例1:将字符串转换为字节

string = "Python is interesting."

# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
print(arr)

输出

b'Python is interesting.'

示例2:创建一个给定整数大小的字节

size = 5

arr = bytes(size)
print(arr)

输出

b'\x00\x00\x00\x00\x00'

示例3:将可迭代列表转换为字节

rList = [1, 2, 3, 4, 5]

arr = bytes(rList)
print(arr)

输出

b'\x01\x02\x03\x04\x05'