Tutorial Study Image

Python bytes()

In python, the bytes function takes an object as input and can produce the corresponding byte object which is immutable(cannot modify). The difference between byte() and bytearray() that bytearray returns a mutable array whereas bytes() returns an immutable object


bytes(a, encoding, error) #where a can be an object or an integer Parameters

bytes() Parameters:

Takes 3 parameters where the first parameter can be an object and if the object is a string the encoding format to be specified as the second parameter.

Parameter Description Required / Optional
Value The value can be an integer, string, or an iterable Optional
Encoding If the string is passed as a parameter, the string encoding to be specified If the first parameter is a string then required
Error To specify what to be done on error Optional

bytes() Return Value
 

Input Return Value
Integer A byte object of the specified size initialized
String as first parameter and encoding as the second parameter The string encoded to bytes
Iterable Byte as the same size as the iterable
No parameter Creates a byte object with no elements

Examples of bytes() method in Python

Example 1: Passing an integer as a parameter to bytes()


print(bytes()

Output:

b'\x00\x00\x00'

Example 2: Passing a string as a parameter to bytes()


string = "Happy day!" 
print(bytes(string, 'utf-8'))
 

Output:

b'Happy day!' 

Example 3: Passing an iterable as a parameter to bytes()


keys = {1 : ‘a’,2:’b’}
print(bytes(keys))
 

Output:

b'\x01\x02' When dictionary is pased its keys will be converted to bytearray

Example 4: Calling the bytes() function with no parameter


print(bytes())
 

Output:

b'' Empty byte