Python bytes()函數返回一個整型數字序列的字節對象,整型數字的取值范圍為:0<=x<256.
官方參考文檔給出的bytes()函數語法格式如下:
class bytes([source[, encoding[, errors]]])
該函數有三個可選參數:
source 可選參數,用于初始化字節對象;
encoding 可選參數,當source為字符串類型時使用該參數指明編碼格式,Python使用str.encode()函數將字符串轉換為字節。
errors 當source為字符串類型,并使用encoding指定的編碼方式編碼失敗時給出的錯誤信息。
在使用bytes()函數時,要注意以下幾條規則:
(1)當沒有傳遞任何參數時,bytes()函數返回空的字節對象;
(2)當source為整型數字時,bytes()函數產生長度為source的null值字節數對象數組;
(3)當source為字符串時,encoding參數是必選參數,以讓bytes()函數按照encoding指定的編碼方式產生字節對象;
(4)如果source是可迭代對象時,如列表、元組等,可迭代對象元素必須是0到255的整型數。
從上面的描述中可以看出,bytes()函數與前面介紹的bytearray()函數非常相似。其不同之處在于,bytes()產生的字節對象是不可變的,而bytearray()函數產生的字節數組是可變的。
該函數返回一個不可變的字節對象。
下面使用幾個例子來說明bytes()函數的具體使用方法。
b = bytes()
print(b)
n = bytes(None)
print(n)
輸出結果如下:
b''
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
n = bytes(None)
TypeError: cannot convert 'NoneType' object to bytes
在Python3.8.2 Shell中的運行情況如下圖所示:
從上面的輸出結果中可以看出,在不給任何參數時,bytes()函數輸出空的字節對象(前面以'b'開始)。
但是不帶參數不等于None,當給定None作為參數時,將引發TypeError錯誤:無法將NoneType對象轉換為字節。
當source為字符串類型時,bytes函數需同時指定encoding參數。
str1 = "Hello World!"
print(bytes(str1,"utf-8"))
print(bytes(str1, "ASCII"))
str2 = "關注公眾號【優雅的代碼】"
print(bytes(str2, "utf-8"))
print(bytes(str2, "ASCII"))
輸出結果如下:
b'Hello World!'
b'Hello World!'
b'/xe5/x85/xb3/xe6/xb3/xa8/xe5/x85/xac/xe4/xbc/x97/xe5/x8f/xb7/xe3/x80/x90/xe4/xbc/x98/xe9/x9b/x85/xe7/x9a/x84/xe4/xbb/xa3/xe7/xa0/x81/xe3/x80/x91'
Traceback (most recent call last):
File "D:/PY/pythonbytes.py", line 7, in <module>
print(bytes(str2, "ASCII"))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)
因為ASCII的編碼范圍是0~127,所以對漢字指定ASCII編碼格式時會報錯:UnicodeEncodeError .
下面再看另外一個例子:
str3 = "abcd"
res = bytes(str3,"utf-8")
print("res=",res)
res[1] = 66
print(res)
輸出結果:
res= b'abcd'
Traceback (most recent call last):
File "D:/PY/pythonbytes.py", line 4, in <module>
res[1] = 66
TypeError: 'bytes' object does not support item assignment
上面這個例子說明bytes()函數產生的字節對象是不可變的,所以可以認為bytes()函數是bytearray()函數的不可變版本。
source參數為整型數時,bytes()函數產生指定長度的null字節對象。
b = bytes(5)
print(b)
輸出結果:
b'/x00/x00/x00/x00/x00'
可迭代對象作為參數時,可迭代對象的元素必須是整型數,否則將引發TypeError錯誤。
b1 = bytes([65,66,67])
print(b1)
b2 = bytes([48,49,50])
print(b2)
輸出結果:
b'ABC'
b'012'
下面再看另外一個例子:
b = bytes(['A','B','C'])
print(b)
輸出結果:
Traceback (most recent call last):
File "D:/PY/pythonbytes.py", line 1, in <module>
b = bytes(['A','B','C'])
TypeError: 'str' object cannot be interpreted as an integer
上面這個例子說明,當使用可迭代對象作為參數時,可迭代對象的元素應該是代表對應字符的整型數。
本文(完)
|
新聞熱點
疑難解答