Hello developers, in this article we will discuss about how to Convert Bytes to String in Python. We know python is a general purpose programming language. In this programming language, Bytes are the sequences of immutable, raw binary data and can have any byte value. Strings are sequences of immutable, Unicode characters which are used to represent text. Converting bytes to strings in Python is actually a fundamental operation when dealing with binary data and also is helpful in many other purpose.
Methods to convert Bytes to String:
There are several method in python to convert Bytes to String, the methods are discussed as following:
Method 1:
Using the decode() method
The most easiest way to convert bytes to a string is by using the decode() method. Here the function decode() interprets the bytes as a specific encoding and returns a string upon calling
The code will be like:
bdta = b'Hello, Meow!' print('\nInput:') print(bdta) print(type(bdta)) sdta = bdta.decode('utf-8')# convertion print(sdta) print(type(sdta))
Method 2:
Using the str() method
Another easy way to convert bytes to a string is by using the str() method. Here the function str() converts the bytes and returns a string upon calling.
The code will be like:
dt = b'Meow Meow' print('\nInput:') print(dt) print(type(dt)) ot = str(dt, 'UTF-8')# convertion print(ot) print(type(ot))
Method 3:
Using the codecs.decode() method
This method codecs.decode() method to decode the bytes into normal String just like the decode() function.
The code will be like:
import codecs dt = b'Meow Meow' print('\nInput:') print(dt) print(type(dt)) # convertion ot = codecs.decode(data) print('\nOutput:') print(ot) print(type(ot))
So, by this way we can easily convert Bytes to String in Python just by using some functions.
[We can also use Pandas and map() too for this conversion .]