DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

bytearray functions in Python

Buy Me a Coffee

*Memo for string, bytes and bytearray functions:

*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=.
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')
Enter fullscreen mode Exit fullscreen mode

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 or int):
    • Don't use iterable=.
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')
Enter fullscreen mode Exit fullscreen mode

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=.
  • The 2nd argument is item(Required-Type:int):
    • Don't use item=.
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')
Enter fullscreen mode Exit fullscreen mode

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=.
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
Enter fullscreen mode Exit fullscreen mode

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'')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Top comments (0)