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
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 |
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 |
print(bytes()
Output:
b'\x00\x00\x00'
string = "Happy day!"
print(bytes(string, 'utf-8'))
Output:
b'Happy day!'
keys = {1 : ‘a’,2:’b’}
print(bytes(keys))
Output:
b'\x01\x02' When dictionary is pased its keys will be converted to bytearray
print(bytes())
Output:
b'' Empty byte