English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Il metodo bytes() restituisce un oggetto bytes immutabile, che viene inizializzato con la dimensione e i dati forniti.
La sintassi del metodo bytes() è:
bytes([source[, encoding[, errors]]])
Il metodo bytes() restituisce un oggetto bytes, che è un'序列 di interi non fissi (non modificabili) con un rango di 0 <= x < 256.
Se si desidera utilizzare la versione mutabile, utilizzarebytearray()metodo.
bytes()具有三个可选参数:
source(可选) -用于源初始化字节的数组。
encoding(可选) -如果source是一个字符串,则为字符串的编码。
errors(可选) -如果source是一个字符串,则在编码转换失败时采取的措施(更多信息:String encoding)
可以通过以下方式使用source参数初始化字节数组:
类型 | 描述 |
---|---|
String | 使用str.encode()将字符串转换为字节必须还提供编码 和可选的错误 |
Integer | 创建一个提供大小的数组,所有数组都初始化为null |
Object | 对象的只读缓冲区将用于初始化字节数组 |
Iterable | 创建一个大小等于可迭代计数的数组,并将其初始化为可迭代元素。必须是0 <= x < 256之间的整数可迭代 |
No source (arguments) | 创建一个大小为0的数组 |
bytes()方法返回给定大小和初始化值的bytes对象。
string = "Python is interesting." # 编码为“utf-8”的字符串 arr = bytes(string, 'utf-8') print(arr)
运行该程序时,输出为:
b'Python is interesting.'
size = 5 arr = bytes(size) print(arr)
运行该程序时,输出为:
b'\x00\x00\x00\x00\x00'
rList = [1, 2, 3, 4, 5] arr = bytes(rList) print(arr)
运行该程序时,输出为:
b'\x01\x02\x03\x04\x05'