Bytearray functions in Python (2)


Buy Me a Coffeeā˜•

*Memo:

  • My post explains bytearray functions (1).
  • My post explains string, bytes and bytearray functions.

remove() can remove the 1st byte matched to value from the bytearray, searching from the left to the right as shown below:

*Memo:

  • The 1st argument is value(Required-Type:int):
  • Error occurs if value doesn’t exist.
v = bytearray(b'ABCAB')

v.remove(ord('B'))
# v.remove(66)

print(v)
# bytearray(b'ACAB')

v.remove(ord('B'))
# v.remove(66)

print(v)
# bytearray(b'ACA')

v.remove(ord('C'))
# v.remove(67)

print(v)
# bytearray(b'AA')

v.remove(ord('a'))
# v.remove(97)
# ValueError: value not found in bytearray
Enter fullscreen mode

Exit fullscreen mode

pop() can remove and throw the byte from index in the bytearray in the range [The 1st index, The last index] as shown below:

*Memo:

  • The 1st argument is index(Optional-Default:-1):
    • -1 means the last index.
    • Don’t use index=.
  • index can be signed indices(zero and positive and negative indices).
  • Error occurs if index is out of range.
v = bytearray(b'ABCAB')

print(v.pop())     # 66
# print(v.pop(4))  # 66
# print(v.pop(-1)) # 66

print(v)
# bytearray(b'ABCA')

print(v.pop(1))    # 66
# print(v.pop(-3)) # 66

print(v)
# bytearray(b'ACA')

print(v.pop(1))    # 66
# print(v.pop(-2)) # 66

print(v)
# bytearray(b'AA')

print(v.pop(-3))
print(v.pop(2))
# IndexError: pop index out of range
Enter fullscreen mode

Exit fullscreen mode

clear() can remove all bytes from the bytearray as shown below:

*Memo:

v = bytearray(b'ABCDE')

v.clear()
# del v[:]

print(v)
# bytearray(b'')
Enter fullscreen mode

Exit fullscreen mode

reverse() can reverse the bytearray as shown below:

*Memo:

v = bytearray(b'ABCDE')

v.reverse()

print(v)
# bytearray(b'EDCBA')
Enter fullscreen mode

Exit fullscreen mode



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *