Python Built in functions in Python
Convetring to bytearray object.
bytearray(object,encoding='utf-8',errors='strict')
object : ( Required ) The object which is to be coverted
encoding : ( Optional ) default is 'utf-8'
errors : ( Optional ) what to do if error occurs.
Returns an mutable array of bytearray.
The bytearray object consist of sequence of integer in the range of 0<=x<=256
Using an integer
my_int=5
my_bytearray = bytearray(my_int)
print(my_bytearray) # bytearray(b'\x00\x00\x00\x00\x00')
Using string
For string argument, we need to give encoding type.
my_str = "plus2net.com"
my_bytearray = bytearray(my_str, encoding='utf-8')
print(my_bytearray) # bytearray(b'plus2net.com')
print(type(my_bytearray)) # <class 'bytearray'>
Using iterable
my_list=[1,2,3,4]
my_bytearray=bytearray(my_list)
print(my_bytearray) # bytearray(b'\x01\x02\x03\x04')
Using errors
This code will generate UnicodeEncodeError:
my_str="plus2net.cÖm"
my_bytearray = bytearray(my_str, encoding='ascii',errors='strict')
print(my_bytearray)
We can keep errors='ignore' to silent the error and continue execution
my_str="plus2net.cÖm"
my_bytearray = bytearray(my_str, encoding='ascii',errors='ignore')
print(my_bytearray) # bytearray(b'plus2net.cm')
We can set errors = 'replace'
my_str="plus2net.cÖm"
my_bytearray = bytearray(my_str, encoding='ascii',errors='replace')
print(my_bytearray) # b'plus2net.cm' # bytearray(b'plus2net.c?m')
using fromhex() method we can use hex value inputs.
mybytearray=bytearray.fromhex('F1F1')
print(mybytearray) # bytearray(b'\xf1\xf1')
Download bytearray.ipynb ( zip ) file ⇓
« All Built in Functions in Python bytes()
← Subscribe to our YouTube Channel here