ByteArray
Bytes
an immutable (can be modified) sequence of integers in the range 0 <=x < 256, the elements of a bytes object cannot be changed
s = b'Hello World!'
print(s, type(s)) # b'Hello World!' bytes
s = 'Hello'
b = bytes(s, encoding = 'utf-8')
print(type(s), type(b)) # unicode, byte string
print(s, b) # Hello b'Hello'
print(b[0], b[1]) # 72 101
ByteArray
a mutable (can be modified) sequence of integers in the range 0 <=x < 256
Bytes and bytearrays are an efficient, byte-based form of strings
# convert list to bytearray
arr = bytearray([97, 98, 99, 99])
print(arr) # bytearray(b'abcc')
# convert string to bytearray
string = 'abcc'
arr = bytearray(string, 'utf-8') # string with encoding 'utf-8'
print(arr) # bytearray(b'abcc')
# convert bytearray to bytes
print(bytes(arr)); # b'abcc'
# modify elements
arr[0] = 10
# access element
print(arr) # bytearray(b'\nbcc')
# slicing
print(arr[:2]) # bytearray(b'\nb')
arr = bytearray("Café", "utf-8")
print(type(arr)) # bytearray
# convert to string
u = arr.decode('utf-8')
print(type(u), u) # unicode, Café
#count
print(arr.count(b'a')) # 1
# in
if 97 in arr:
print('a in arr ...')
# concatenation
print(arr+bytearray(b'dddddddd'))
#conver to list
print(list(arr)) # [67, 97, 102, 195, 169]
#append
arr.append(97)
print(arr) # bytearray(b'Caf\xc3\xa9a')
#delete
del arr[:2]
print(arr) # bytearray(b'f\xc3\xa9a')
#insert
arr.insert(0, 98)
print(arr) # bytearray(b'bf\xc3\xa9a')
#replace
arr = arr.replace(b'b', b'c')
print(arr) # bytearray(b'cf\xc3\xa9a')
Reference