The bytes()
function in Python is used to create a new immutable bytes object. It can take different types of arguments and convert them into a bytes object.Here is the syntax for the bytes()
function:
bytes(source, encoding, errors)
source
argument specifies the input that will be converted to bytes. It can be a string, iterable, integer, or a buffer-like object.encoding
parameter specifies the character encoding to be used while converting a string to bytes. If not provided, the default encoding is 'utf-8'
.errors
parameter specifies how encoding and decoding errors should be handled. Possible values are 'strict'
(default), 'ignore'
, 'replace'
, 'xmlcharrefreplace'
, 'backslashreplace'
, and others.Here are some examples of using the bytes()
function:
my_string = "Hello, world!"
my_bytes = bytes(my_string, encoding='utf-8')
print(my_bytes)
my_list = [65, 66, 67]
my_bytes = bytes(my_list)
print(my_bytes)
my_buffer = bytearray([72, 101, 108, 108, 111])
my_bytes = bytes(my_buffer)
print(my_bytes)
The bytes()
function returns a new bytes object that represents the input data. The resulting bytes object is immutable, meaning its contents cannot be modified after creation.