Python provides the bytes()
method in order to convert provided data or objects into the byte type. The byte type may contain values from 0 to 255. Different types can be converted into the byte type using the byte() method.
bytes() Method Syntax
The bytes() method has the following syntax.
bytes(DATA,ENCODING,ERRORS)
- DATA is the string or int or list or another type that will be converted into a byte. This parameter is required.
- ENCODING is an optional parameter that is used to specify the encoding for string type.
- ERRORS is a rarely used optional parameter used to take action when there is an error.
Convert String To Byte
A string can be converted into a byte by using the bytes() method. Every character in the string is converted one by one. As different strings have different encodings we should provide the encoding type as a second parameter.
s = "pythontect"
a = bytes(s,'utf-8')
print(a)
b'pythontect'
We can see that the output starts with the letter b
which means the printed data is byte type.
Convert List To Byte
A list may contain single or more items. These items can be converted into the byte using the bytes()
.
numbers = [1,2,3,4]
b = bytes(numbers)
print(b)
b'\x01\x02\x03\x04'
We can see that the output of every item is converted one by one into the byte type.