bytes() Builtin Function
Python - bytes()
Python bytes() builtin function returns an empty bytes object when no arguments passed, bytes object of specific size when size is specified, or a bytes object created from the given string object and encoding.
In this tutorial, you will learn the syntax of bytes() function, and then its usage with the help of example programs.
Syntax
The syntax of bytes()
function is
bytes(x, encoding, error)
where
Parameter | Description |
---|---|
source | The source for creating bytes object. If source is an integer, then bytes() returns a bytes object of this size.If source is string, then bytes() returns bytes object created using the characters in the string, and specified encoding. |
encoding | The encoding to be used, if source is a string. |
errors | The action to be performed if encoding fails. |
Note: Since bytes object is immutable, individual byte values in the bytes object cannot be modified.
Examples
1. Create bytes object of specific size
In the following program, we pass a positive integer to bytes()
function, to create a bytes object of the specified size. '\x00'
is initial value for the bytes in the bytes object.
Python Program
x = 5
output = bytes(x)
print(f'x : {x}')
print(f'bytes(x) : {output}')
Output
x : 5
bytes(x) : b'\x00\x00\x00\x00\x00'
2. Create bytes object from a string
In the following program, we pass a string value to bytes()
function, to create bytes object from the input string. We specify the encoding 'utf-8'
.
Python Program
x = 'apple'
output = bytes(x, 'utf-8')
print(f'x : {x}')
print(f'bytes(x) : {output}')
Output
x : apple
bytes(x) : b'apple'
Summary
In this tutorial of Python Examples, we learned the syntax of bytes() function, and how to create a bytes object of specific size, or a bytes object initialised using string argument, with examples.