Convert bytes to string in Python
This post will discuss how to convert bytes to a string in Python.
1. Using decode() function
The idea is to use the bytes.decode() function for decoding the given bytes to return a string. It takes the encoding used to encode the data to bytes. If no encoding is specified, the utf-8 encoding is applied.
|
1 2 3 4 5 6 7 8 9 10 |
import sys if __name__ == '__main__': b = b'abc' encoding = sys.getdefaultencoding() s = b.decode(encoding) print(s) # abc |
2. Using String constructor
Alternatively, you can use the string constructor str(data, encoding) to get a string decoded from the given bytes using the given encoding.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': b = b'abc' encoding = 'utf-8' s = str(b, encoding) print(s) # abc |
3. Using map() function
You can get the string constructed from the bytes array by mapping each byte to a character using the chr function. Here’s what the code would look like:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': bytes_data = [97, 98, 99] s = ''.join(map(chr, bytes_data)) print(s) # abc |
That’s all about converting bytes to string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)