bytearray(object,encoding='utf-8',errors='strict')
object : ( Required ) The object which is to be covertedmy_int=5
my_bytearray = bytearray(my_int)
print(my_bytearray) # bytearray(b'\x00\x00\x00\x00\x00')
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')
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')
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.