Convert bytes to string in Python
In python 3, you can convert bytes to string using:
and you can convert string to bytes using:
We can convert bytes to String using bytes class decode() instance method, So you need to decode the bytes object to produce a string. In Python 3 , the default encoding is "utf-8" , so you can use directly:
which is equivalent to:
In Python 2 , encoding defaults to the default string encoding . Thus, you should use:
We can convert string to bytes using encode() instance method, So you need to encode the string object to produce a byte.
Also, Python bytes() method returns a bytes object of the given size and initialization values.
Both of the above methods to convert a string to bytes are perfectly fine. String encode() and decode() method provides symmetry whereas bytes() constructor is more object-oriented and readable approach. You can choose any of them based on your preference.
Python makes a clear distinction between bytes and strings . Bytes objects contain raw data — a sequence of octets — whereas strings are Unicode sequences . Conversion between these two types is explicit: you encode a string to get bytes, specifying an encoding (which defaults to UTF-8); and you decode bytes to get a string. Clients of these functions should be aware that such conversions may fail, and should consider how failures are handled.