Python Bytes to String
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 of bytes.decode()
The syntax of bytes.decode() method is
bytes.decode(encoding)
where encoding specifies how to decode the bytes sequence.
decode() method returns the decoded string.
Examples
1. Convert bytes object 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)
Output
52s3a6
2. Convert hex bytes to a string value
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)
Output
hello
3. Convert hex bytes to a string using utf-16 encoding
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)
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.