bytes(object,encoding='utf-8',errors='strict')
object : ( Required ) The object which is to be convertedmy_int=5
my_bytes = bytes(my_int)
print(my_bytes) # b'\x00\x00\x00\x00\x00'
my_str = "plus2net.com"
my_bytes = bytes(my_str, encoding='utf-8')
print(my_bytes) # b'plus2net.com'
print(type(my_bytes)) # <class 'bytes'>
Using iterable
my_list=[1,2,3,4]
my_bytes=bytes(my_list)
print(my_bytes) # b'\x01\x02\x03\x04'
my_str="plus2net.cÖm"
my_bytes = bytes(my_str, encoding='ascii',errors='strict')
print(my_bytes)
We can keep errors='ignore' to silent the error and continue execution
my_str="plus2net.cÖm"
my_bytes = bytes(my_str, encoding='ascii',errors='ignore')
print(my_bytes) # b'plus2net.cm'
We can set errors = 'replace'
my_str="plus2net.cÖm"
my_bytes = bytes(my_str, encoding='ascii',errors='replace')
print(my_bytes) # b'plus2net.cm' # b'plus2net.c?m'
using fromhex() method we can use hex value inputs.
mybytes=bytes.fromhex('F1F1')
print(mybytes) # 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.