在本教程中,我們將借助示例了解 Python bytes() 方法。
bytes()
方法返回使用給定大小和數據初始化的不可變字節對象。
示例
message = 'Python is fun'
# convert string to bytes
byte_message = bytes(message, 'utf-8')
print(byte_message)
# Output: b'Python is fun'
bytes() 語法
用法:
bytes([source[, encoding[, errors]]])
bytes()
方法返回一個字節對象,該對象是 0 <=x < 256
範圍內的不可變(無法修改)整數序列。
如果要使用可變版本,請使用 bytearray() 方法。
參數:
bytes()
采用三個可選參數:
- 來源(可選)- 初始化字節數組的源。
- 編碼(可選)- 如果源是字符串,則字符串的編碼。
- 錯誤(可選)- 如果源是一個字符串,當編碼轉換失敗時采取的行動(閱讀更多:String encode)
source 參數可用於通過以下方式初始化字節數組:
類型 | 說明 |
---|---|
String | 使用 str.encode() 將字符串轉換為字節 還必須提供編碼並且可以選擇錯誤 |
Integer | 創建一個提供大小的數組,全部初始化為 null |
Object | 對象的隻讀緩衝區將用於初始化字節數組 |
Iterable | 創建一個大小等於可迭代計數並初始化為可迭代元素的數組 必須是 0 <= x < 256 之間的整數的可迭代 |
無來源(參數) | 創建一個大小為 0 的數組 |
返回:
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'
相關用法
- Python bytes()用法及代碼示例
- Python bytearray()用法及代碼示例
- Python base64.b64decode()用法及代碼示例
- Python bokeh.plotting.figure.asterisk()用法及代碼示例
- Python binary轉string用法及代碼示例
- Python base64.b32decode()用法及代碼示例
- Python bokeh.plotting.figure.annular_wedge()用法及代碼示例
- Python bool()用法及代碼示例
- Python base64.b85encode()用法及代碼示例
- Python bokeh.plotting.figure.circle()用法及代碼示例
- Python bz2.decompress(s)用法及代碼示例
- Python bokeh.plotting.figure.circle_cross()用法及代碼示例
- Python bokeh.plotting.figure.bezier()用法及代碼示例
- Python bokeh.plotting.figure.diamond()用法及代碼示例
- Python base64.decodebytes(s)用法及代碼示例
- Python base64.decodestring(s)用法及代碼示例
- Python binary轉ASCII用法及代碼示例
- Python base64.urlsafe_b64decode(s)用法及代碼示例
- Python MongoDB bulk_write()用法及代碼示例
- Python base64.b16encode()用法及代碼示例
注:本文由純淨天空篩選整理自 Python bytes()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。