bytes()
function is used to find the new bytes
object in Python which is an immutable (cannot be modified) sequence of integers in the range, 0 <=x < 256
. For using muteable version use bytearray() function.
bytes()
function is a part of Python Built-in Functions.
Syntax of bytes()
Function
The syntax of bytes()
function in Python is:
bytes([source[, encoding[, errors]]])
Parameters of bytes()
Function in Python
source
– Where source
is the initialization of bytes array. This could be a string, integer, object, iterable and an array of size 0. This parameter is optional.encoding
– Where encoding
is the encoding of the string. This parameter is also optional.errors
– Where errors
are actions that needed to take when encoding fails. This parameter is also optional.
Compatibility
bytes()
function is only available and compatible with Python 3.x
.
Return Value of bytes()
Function in Python
bytes()
function returns a new immutable “bytes” object initialized with the given size and data.
Python bytes()
Function Example 1
stringValue = "This is my Test String." # string value passed to bytes with utf-8 encoding parameter myArray = bytes(stringValue, 'utf-8') print(myArray)
Output:
b'This is my Test String.'
Python bytes()
Function Example 2
integerValue = 7 myArray = bytes(integerValue) print(myArray)
Output:
b'\x00\x00\x00\x00\x00\x00\x00'
Python bytes()
Function Example 3
elementList = [5,6,7,8] myArray = bytes(elementList) print(myArray)
Output:
b'\x05\x06\x07\x08'