In this article we will discuss about the byte() function in python programming language with the help of examples.
Python byte() function
By using the built-in python function, we can convert the collection of integers or strings into immutable byte sequence. In simple terms, the python byte() method is used to return an object byte of specified size and data and is immutable in the range [0 <= x < 256]
Syntax
bytes([source[, encoding[, errors]]])
Parameter of Python byte() function
Python byte() function takes three types of optional parameter which are as follows;
• source- A source in order to initialize the array of bytes.
• encoding- If the source is string, then for the encoding of the string.
• error- If the encoding fails it takes action.
Return value of Python byte() function
The python method is used to return an object byte of specified size and data and is immutable in the range [0 <= x < 256]
Example 1: How to convert string to bytes
str1 = "Python is Programming Language."# string with encoding 'utf-8'
array = bytes(str1, 'utf-8')
print(array)
Output
b'Python is Programming Language.'
Example 2: How to create a byte of given integer size
num = 7array = bytes(num)
print(array)
Output
b'\x00\x00\x00\x00\x00\x00\x00'
Example 3: How to convert iterable list to bytes
li = [11, 12, 13, 14, 15]array = bytes(li)
print(array)
Output
b'\x0b\x0c\r\x0e\x0f'