bytes(): returns an immutable sequence of bytes

Converting to bytes object.
bytes(object,encoding='utf-8',errors='strict')
object : ( Required ) The object which is to be converted
encoding : ( Optional ) default is 'utf-8'
errors : ( Optional ) what to do if error occurs.
Returns an immutable array of bytes.
The bytes object consist of sequence of integer in the range of 0<=x<=256

Using an integer

my_int=5
my_bytes = bytes(my_int)
print(my_bytes) #   b'\x00\x00\x00\x00\x00'

Using string

For string argument, we need to give encoding type.
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'

Using errors

This code will generate UnicodeEncodeError:
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'

All Built in Functions in Python bytearray()

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate 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.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer