We utilize the Python bytes() method to manipulate binary data in the program. The byte is a digital information unit that typically consists of 8 bits each of which consists of a 0 or 1. A byte is a computer architecture term for memory storage that encodes a single character of text in a computer. The purpose of this article is to demonstrate and explain the operation of interconversion of various data formats to Python bytes().
Definition
- Python bytes() function is used to convert an object to an immutable (cannot be modified) byte object of the given size and data.
- The Python bytes() function returns a byte’s object, which is an immutable series of integer numbers ranging from 0 to 256.
Python bytes() function
-
Syntax
Let us look at the syntax of Python bytes() built-in function:
bytes(source, encoding, errors)
-
bytes() Parameters
Python bytes() function accepts 3 parameters. All these 3 parameters are optional.
source = used to initialize an array of byte’s object
encoding = used only when the source is a string
errors = the actions to be undertaken, if the encoding conversion fails of the string source
Note – If the source is a string, then we must compulsorily pass the other 2 parameters. If not, then the Python interpreter will return TypeError.
-
Return value from bytes() function
The bytes() function returns a byte’s object with the specified size and initialization parameters.
Various source parameters | |
source type | Description |
String | str.encode is used to convert the string to bytes(). The encoding and errors parameters must also be provided. |
Integer | Returns a null-initialized array of size. |
Object | Returns a read-only object buffer that will be used to initialize the bytes array. |
Iterable | Creates an array with the same size as the iterable count. It must be iterable over numbers between 0 <= x <= 256. |
No source
(no arguments) |
Creates an array of size 0 |
Example 1: Convert string to bytes
Simply supply the string as the source argument and the encoding as the encoding argument to convert a string to bytes. The error argument is optional and can be specified as per the programmer’s need.
Example 1
# Python program to illustrate bytes() with string source
txt = 'Hello World'
arr = bytes(txt, 'utf-8')
print(arr)
print('')
# source string without other parameters
string = 'Welcome Home'
arr2 = bytes(string) # as there are no other parameters specified, it will throw TypeError
print(arr2)
Output
b'Hello World'
Traceback (most recent call last):
File "", line 8, in
TypeError: string argument without an encoding
Example 2
string = 'Prógrammïng'
# encoding = ascii, errors are ignored
z = bytes(string, 'ascii', errors = 'ignore')
print('Byte conversion:', z)
# encoding = ascii, errors are replaced
z = bytes(string, 'ascii', errors = 'replace')
print('Byte conversion:', z)
# encoding = ascii, errors are strict, will throw error
z = bytes(string, 'ascii', errors = 'strict')
print('Byte conversion:', z)
Output
Byte conversion: b'Prgrammng'
Byte conversion: b'Pr?gramm?ng'
Traceback (most recent call last):
File "", line 12, in
UnicodeEncodeError: 'ascii' codec can't encode character '\xf3'
in position 2: ordinal not in range(128)
Example 2: Create a byte of a given Integer size
If the source parameter is an Integer, Python’s bytes() method will build an array of the specified integer size, all of which will be initialized to NULL.
Example
size1 = 1
z = bytes(size1)
print('Byte conversion:', z)
size2 = 3
z = bytes(size2)
print('Byte conversion:', z)
Output
Byte conversion: b'\x00'
Byte conversion: b'\x00\x00\x00'
Example 3: Convert iterable list to bytes
If the source parameter is iterable, such as Lists in Python, it outputs an array with elements equal to iterable elements (range 0 to 256).
Example
even_num = [2, 4, 6, 8, 10]
arr = bytes(even_num)
print(arr)
Output
b'\x02\x04\x06\x08\n'
Difference between bytes() and bytearray()
The main difference between Python bytes() and bytearray() is that the bytes() returns an object that cannot be edited i.e. immutable, but bytearray() returns a new array of bytes that can be modifiable objects i.e. mutable.
Frequently Asked Questions
Q1. What are bytes in Python?
In computer programming, byte is a digital information unit that typically consists of 8 bits each of which consists of either a 0 or 1. A byte is a computer architecture term for memory storage that encodes a single character of text in a computer. Each byte can store a string of bits that must be combined into a larger unit for various application reasons.
Q2. How do you find bytes in Python?
In order to find out the bytes of any iterable object in Python, we use the bytes() built-in function. Python bytes() function is used to convert an object to an immutable byte object of the given size and data.
Syntax
bytes(source, encoding, errors)
Python bytes() function accepts 3 parameters. All these 3 parameters are optional.
source = used to initialize an array of byte’s object
encoding = used only when the source is a string
errors = the actions to be undertaken, if the encoding conversion fails of the string source
Example
mytext = 'Goôd Morñing'
x = bytes(mytext, 'ascii', errors = 'ignore')
print('Byte conversion of', mytext, 'is:', x)
print('')
x = bytes(mytext, 'ascii', errors = 'replace')
print('Byte conversion of', mytext, 'is:', x)
print('')
x = bytes(mytext, 'ascii', errors = 'strict')
print('Byte conversion of', mytext, 'is:', x)
Output
Byte conversion of Goôd Morñing is: b'God Moring'
Byte conversion of Goôd Morñing is: b'Go?d Mor?ing'
Traceback (most recent call last):
File "", line 11, in
UnicodeEncodeError: 'ascii' codec can't encode character '\xf4'
in position 2: ordinal not in range(128)
Q3. How many bytes is a string in Python?
Each character of a string is allocated memory space of 1 byte in Python. This can be understood by using the following method –
Using len()+encode()
Example
mytext = 'Python'
x = len(mytext.encode('utf-8'))
print('Length of string in Bytes:', x)
Output –
Length of string in Bytes: 6
Q4. How can you convert a list to bytes in Python?
If the source parameter is iterable, such as Lists in Python, it outputs an array with elements equal to iterable elements (range 0 to 256). Lists containing integers can only be converted to bytes using the Python bytes() function. If the lists contain string values, the Python interpreter will throw an error.
Example
mylist = [1, 2, 3, 4, 5, 6]
res = bytes(mylist)
print('Byte conversion of list:', res)
Output
Byte conversion of list: b'\x01\x02\x03\x04\x05\x06'
Leave a Reply