The byte is a data type that stores values in octal format. The string data type is used to store data as characters which can be formatted in different encodings. Python provides encode(), decode() methods with the b byte conversion keyword. For example, the subprocess module Popen() method returns the output as a byte format.
Sample Byte List
Before starting to learn about how to convert the byte to string we will create a sample byte list in order to use in these examples. Bytes are expressed as ASCII character table like below. In the following list the string is “Like PythonTect.” but expressed as a byte list.
bytelist = [76,111,118,101,32,80,121,116,104,111,110,84,101,99,116,46] bytechars=b"Like PythonTect."
Print Byte As String with print() Method
The print() method supports the automatic conversion of the given byte value as a string. It can be used to print a byte value in the command line as a string without working on conversion. But the printed byte value will be prefixed with the b keyword in order to express that this is a byte value like below.
bytechars=b"Like PythonTect." print(bytechars)
Convert Bytes To String with decode() Method
The byte data type provides the decode() method in order to convert byte into the string. decode() method will be called over the byte data and return a string data.
bytechars=b"Like PythonTect." print("This is byte value: ") print(bytechars) print("This is string value: "+bytechars.decode())
Convert Bytes To String with Specified Encoding
The decode() method is used to convert byte data into a string. As string data can be stored with different encodings the true encoding should be used for decode operation. The encoding format is specified as a parameter to the decode() method. “utf-8” is one of the most popular encoding formats which supports most of the world languages. But the default encoding format used if the encoding format is not specified for the decode() method is “ascii”.
bytechars=b"Like PythonTect." print("This is byte value: ") print(bytechars) print("This is string value: "+bytechars.decode("ascii"))
Convert Bytes To String with join() and chr() Methods
Byte values can be also stored as a list where every byte value is one item in the list. In order to convert this type of byte list into a string the join() and chr() methods can be used. The chr() method will be used with the map() method in order to convert a single byte value into a single character and the join() method will join all the converted characters into a single string.
bytelist = [76,111,118,101,32,80,121,116,104,111,110,84,101,99,116,46] str = "".join(map(chr,bytelist)) print(str)