Contents
Python bytes to String
To convert Python bytes object to String, you can use bytes.decode() method.
In this tutorial, we will learn the syntax of bytes.decode() method, and how to use decode() method to convert or decode a python bytes to a string object.
Syntax – bytes.decode()
The syntax of bytes.decode() method is
bytes.decode(encoding)
Run where encoding specifies how to decode the bytes sequence.
decode() method returns the decoded string.
Example 1: Bytes to String
In this example, we will decode bytes sequence to string using bytes.decode() method.
Python Program
bytesObj = b'52s3a6'
string = bytesObj.decode('utf-8')
print(string)
Run Output
52s3a6
Example 2: Hex Bytes to String
In this example, we will take a bytes sequence which contains hexadecimal representation of bytes, and have them converted to string.
Python Program
bytesObj = b'\x68\x65\x6C\x6C\x6F'
string = bytesObj.decode('utf-8')
print(string)
Run Output
hello
Example 3: Hex Bytes to String using utf-16
You can decode the bytes sequence in the required format.
In this example, we will take a bytes sequence which contains hexadecimal representation of bytes, and have them converted to string using utf-16 format.
Python Program
bytesObj = b'\x68\x00\x65\x00\x6c\x00\x6c\x00\x6f\x00'
string = bytesObj.decode('utf-16')
print(string)
Run Output
hello
As, we are using utf-16, it takes 4 hex digits to make a utf-16 character. So, \x68\x00
is converted to a single utf-16 character h
.
Summary
In this tutorial of Python Examples, we learned how to convert bytes sequence to string.