*Memo for string, bytes and bytearray functions:
- My post explains ord(), sorted() and reversed().
*Memo for a string, bytes and bytearray:
bytearray.append() can add a byte to the end of the bytearray as shown below:
*Memo:
- The 1st argument is
item
(Required-Type:int
):- Don't use
item=
.
- Don't use
v = bytearray(b'ABC')
v.append(ord('D'))
# v.append(68)
print(v)
# bytearray(b'ABCD')
v.append(ord('E'))
# v.append(69)
print(v)
# bytearray(b'abcde')
bytearray.extend() can add a bytes or bytearray to the end of the bytearray as shown below:
*Memo:
- The 1st argument is
iterable
(Required-Type:Bytes-like-object orint
):- Don't use
iterable=
.
- Don't use
v = bytearray(b'ABC')
v.extend(b'D')
# v.extend(bytearray(b'D'))
print(v)
# bytearray(b'ABCD')
v.extend(b'EF')
# v.extend(bytearray(b'EF'))
print(v)
# bytearray(b'ABCDEF')
v.extend(b'')
# v.extend(bytearray(b''))
print(v)
# bytearray(b'ABCDEF')
bytearray.insert() can add a byte to the selected index in the bytearray as shown below:
*Memo:
- The 1st argument is
index
(Required-Type:int
):- Don't use
index=
.
- Don't use
- The 2nd argument is
item
(Required-Type:int
):- Don't use
item=
.
- Don't use
v = bytearray(b'abcd')
v.insert(2, ord('X'))
# v.insert(2, 88)
print(v)
# bytearray(b'abXcd')
v.insert(0, ord('Y'))
# v.insert(0, 89)
print(v)
# bytearray(b'YabXcd')
v.insert(6, ord('Z'))
# v.insert(6, 90)
print(v)
# bytearray(b'YabXcdZ')
bytearray.remove() can remove a byte from the bytearray as shown below:
*Memos:
- The 1st argument is
value
(Required-Type:int
):- Error occurs if
value
doesn't exist. - Don't use
value=
.
- Error occurs if
v = bytearray(b'abcd')
v.remove(ord('b'))
# v.remove(98)
print(v)
# bytearray(b'acd')
v.remove(ord('c'))
# v.remove(99)
print(v)
# bytearray(b'ad')
v.remove(ord('e'))
# v.remove(101)
# ValueError: value not found in bytearray
bytearray.clear() can remove all bytes from the bytearray as shown below:
*Memo:
- It has no arguments.
v = bytearray(b'abcde')
v.clear()
# del v[:]
print(v)
# bytearray(b'')
bytearray.pop() can remove and throw a byte from the bytearray as shown below:
*Memo:
- The 1st argument is
index
(Optional-Default:-1
):-
-1
means the last byte. - Don't use
index=
.
-
v = bytearray(b'abcde')
print(v.pop())
# print(v.pop(4))
# 101
print(v)
# bytearray(b'abcd')
print(v.pop(2))
# 99
print(v)
# bytearray(b'abd')
bytearray.reverse() can reverse the bytearray as shown below:
*Memo:
- It has no arguments.
v = bytearray(b'abcde')
v.reverse()
print(v)
# bytearray(b'edcba')
Top comments (0)