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
#!/usr/bin/python
s = b'Hello World!'
print(s, type(s))
#!/usr/bin/python
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
#!/usr/bin/python
# convert list to bytearray
arr = bytearray([97, 98, 99, 99]);
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')
#!/usr/bin/python
arr = bytearray("Café", "utf-8");
print(type(arr))
# convert to string
s = str(arr) # unicode
print(type(s), s); # unicode, bytearray(b'Caf\xc3\xa9')
u = arr.decode('utf-8')
print(type(u), u) # unicode, Café
#count
print(arr.count(b'a'));
# 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)
#delete
del arr[:2];
print(arr)
#insert
arr.insert(0, 98);
print(arr);
#replace
arr = arr.replace(b'b', b'c');
print(arr);
Reference