一、什麼是Bytearray
Bytearray是Python中的一種可變序列,它是由一個可變大小的字節數組組成。bytearray對象與bytes對象類似,但有一個重要區別,即bytearray對象可以修改,是可變的,在修改數據方面比bytes對象更靈活。
二、創建Bytearray對象
創建Bytearray對象有多種方法:
1. 直接使用bytearray()
b = bytearray() print(b) # 輸出bytearray(b'')
2. 使用bytearray()和參數size
可以指定Bytearray對象的長度,創建指定大小的字節數組對象。
b = bytearray(5) print(b) # 輸出bytearray(b'\x00\x00\x00\x00\x00')
3. 使用bytearray()和bytes
可以使用已有的bytes對象來創建Bytearray對象。
b = bytes(b"hello") b1 = bytearray(b) print(b1) # 輸出bytearray(b'hello')
三、Bytearray對象的操作
1. 修改字節串
Bytearray對象允許對字節串進行修改和刪除操作。
b = bytearray(b"hello") b[1] = 107 # 修改第二個字節,將其變為ASCII碼為107的字符 print(b) # 輸出bytearray(b'hkll')
2. 添加字節串
Bytearray對象可以使用append()方法往其末尾添加字節串。
b = bytearray(b"hello") b.append(33) # 在字節串末尾添加ASCII碼為33的字符 print(b) # 輸出bytearray(b'hello!')
3. 插入字節串
Bytearray對象可以使用insert()方法在任意位置插入字節串。
b = bytearray(b"hello") b.insert(0, 104) # 在第一個位置插入ASCII碼為104的字符 print(b) # 輸出bytearray(b'hello')
4. 刪除字節串
Bytearray對象可以使用del語句或者remove()方法刪除指定位置或指定值的字節串。
b = bytearray(b"hello") del b[1] # 刪除第二個字節 print(b) # 輸出bytearray(b'helo') b.remove(108) # 刪除ASCII碼為108的字符 print(b) # 輸出bytearray(b'heo')
5. 截取字節串
Bytearray對象可以使用切片(slice)操作截取任意位置的子串。
b = bytearray(b"hello") print(b[1:4]) # 輸出bytearray(b'ell')
四、Bytearray對象的轉換
1. 轉為bytes對象
Bytearray對象可以使用bytes()方法轉換為bytes對象。
b = bytearray(b"hello") b1 = bytes(b) print(b1) # 輸出b'hello'
2. 轉為字符串
Bytearray對象可以使用decode()方法轉換為字符串。
b = bytearray(b"hello") s = b.decode() print(s) # 輸出hello
3. 轉為列表
Bytearray對象可以使用list()方法轉換為列表,列表中的元素是字節。
b = bytearray(b"hello") lst = list(b) print(lst) # 輸出[104, 101, 108, 108, 111]
五、總結
通過本文的介紹,我們了解到了Bytearray對象的創建、修改、添加、插入、刪除、截取以及與其他類型的轉換等操作方法,它的靈活性使得在處理二進制數據時更加方便,是Python中常用的數據類型之一。
原創文章,作者:MNIL,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/142466.html