5 Ways to Convert bytes to string in Python

In python, we have discussed many concepts and conversions. But sometimes, we come to a situation where we need to convert bytes to string in python. In this tutorial, we will be discussing how to convert bytes to strings in python. As the conversion of elements has been a handy utility as it offers it in a much simpler way than other languages.

What is Bytes data type in Python?

If you are familiar with python, then you must already be knowing about the byte data type. But if someone is not friendly with Python, then we will be explaining this concept. Let’s understand this with the following example.

str1 = 'Python Pool'  
print(type(str1))  
str2 = b'Python Pool'  
print(type(str2)) 

Output:

<class 'str'>
<class 'bytes'>

Explanation:

  • We have defined two strings with the same value as ‘Python Pool.’
  • Both the values are looking similar, but their data type is not similar.
  • The first string variable, i.e., str1, is of string data type, and another one is the byte data type.
  • The second string is prefixed with the ‘b,’ which says that it produces byte data type instead of the string data type.
  • Hence, you can see the output.

Ways to convert bytes to string

Here, we will discussing all the different ways through which we can convert bytes to string:

1. Using map() without using b prefix

In this example, we will be using the map function to convert a byte to a string without using the prefix b. Let us look at the example for understanding the concept in detail.

byte = [97, 98, 99]
 
s = ''.join(map(chr, byte))
print(s)

Output:

abc

Explanation:

  • Firstly, we have taken a list as input which is stored in the variable byte.
  • Then, we have applied the join() function inside, in which we have applied the map function with the characters of the element in the list and byte as the parameters. After the conversion, it will join all the characters.
  • At last, we have printed the output.
  • Hence, you can see the string with the prefix b.

2. Using Decode() function to convert bytes to string in Python

In this example, we will be using the decode() function. The function is used to convert from the encoding scheme, in which the argument string is encoded to the desired encoding scheme. This works just opposite to the encode. Let us look at the example for understanding the concept in detail.

#convert bytes to string using decode()

str = b'Pythonpool'

# display input
print('\nInput:')
print(str)
print(type(str))

# converting
output = str.decode()

# display output
print('\nOutput:')
print(output)
print(type(output))

Output:

Input:
b'Pythonpool'
<class 'bytes'>

Output:
Pythonpool
<class 'str'>

Explanation:

  • Firstly, we have taken an input string in the variable str with the value as ‘Pythonpool.’
  • Then, we have displayed the input string and also printed the data type of the string.
  • After that, we have applied the decode() function and stored the output in the output variable.
  • Finally, we have printed the string in the output variable and the data type of that variable.
  • Hence, you can see the output.

3. Using the str() function to convert bytes to string in Python

In this example, we will be using the str() function. The function is used to return the string version of the object. Let us look at the example for understanding the concept in detail.

# convert bytes to string using str()
str = b'Pythonpool'

# display input
print('\nInput:')
print(str)
print(type(str))

# converting
output = str(str, 'UTF-8')

# display output
print('\nOutput:')
print(output)
print(type(output))

Output:

Input:
b'Pythonpool'
<class 'bytes'>

Output:

Pythonpool
<class 'str'>

Explanation:

  • Firstly, we have taken an input string in the variable str with the value as ‘Pythonpool.’
  • Then, we have displayed the input string and also printed the data type of the string.
  • After that, we have applied the str() function with both of its parameters as the input string and UTF-8 and stored the output in the output variable.
  • Finally, we have printed the string in the output variable and the data type of that variable.
  • Hence, you can see the output.

4. Using codecs.decode() function to convert bytes to string in Python

In this example, we will be using codecs.decode() function. This function is used to decode the binary string into normal form. Let us look at the example for understanding the concept in detail.

#convert bytes to string using codecs.decode()
# import codecs
import codecs

str = b'Pythonpool'

# display input
print('\nInput:')
print(str)
print(type(str))

# converting
output = codecs.decode(str)

# display output
print('\nOutput:')
print(output)
print(type(output))

Output:

Input:
b'Pythonpool'
<class 'bytes'>

Output:
Pythonpool
<class 'str'>

Explanation:

  • Firstly, we have imported the codecs module.
  • After that, we have taken an input string in the variable str with the value as ‘Pythonpool.’
  • Then, we have displayed the input string and also printed the data type of the string.
  • After that, we have applied the codecs.decode() function and stored the output in the output variable.
  • Finally, we have printed the string in the output variable and the data type of that variable.
  • Hence, you can see the output.

5. Using pandas to convert bytes to string in Python

In this example, we will be importing the pandas’ library. Then, we will take the input dataset and apply the decode() function. Let us look at the example for understanding the concept in detail.

import pandas as pd
d = {'column' : [b'abcde', b'dog', b'cat1', b'bird1', b'elephant1']}
df = pd.DataFrame(data=d)

output = df['column'].str.decode("utf-8")
print(output)

Output:

0        abcde
1          dog
2         cat1
3        bird1
4    elephant1
Name: column, dtype: object

Explanation:

  • Firstly, we will import the pandas’ library with an alias name as pd.
  • Then, we will take the input dataframe.
  • After that, we will apply the pandas. dataframe with data=d as the parameter.
  • Then, we will apply the decode() function in the data.
  • At last, we will print the output.
  • Hence, you can see the output.

How decode() can remove the b prefix of a string

Decode() function is used to remove the prefix b of a string. The function is used to convert from the encoding scheme, in which the argument string is encoded to the desired encoding scheme, through which the b prefix gets removed. Let us look at the example for understanding the concept in detail.

str_object = b'Python Pool'
print(str_object)
str_object = str_object.decode()
print(str_object)

Output:

b'Python Pool'
Python Pool

Difference between byte and string data type in Python

String data type

It is a sequence of Unicode characters (encoded in UTF -16 or UTF-32 and entirely depends on Python’s compilation).

Byte data type

It is used to represent an integer between 0 and 255, and we can denote it as ‘b’ or ‘B.’

Python Bytes to String base64

We can change bytes to a base64 string and vice versa with the help of base64 library.  Let’s have a look at the given example: 

import base64
encodedans = base64.b64encode(b'encoded data')

#to get the data back, use decode function 

olddata = base64.b64decode(encodedans)

So you can decode it back to original data. 

Python Bytes to String Without Decoding

Without decoding, we can change the bytes to string format using str function. 

Example code: 

str = b'Python'
# input is : 

print(str)

print(type(str))

output = str(str, 'UTF-8')

# output in str format is : 

print('\n')

print(output)

print(type(output))

python bytes to string hex

 We can convert byte data to hexadecimal format string using the hex() function. It is easy to use. You just need to supply the thr byte code. 

Example:

byte_data="\xff\xfe\x00".encode("utf-16")
print("byte to be converted:",byte_data)

print("byte converted to hexadecimal value:",byte_data.hex())

print("Type:",type(byte_data.hex()))

So the output is:

byte to be converted: b'\xff\xfe\xff\x00\xfe\x00\x00\x00'
byte converted to hexadecimal value: fffeff00fe000000
Type: <class 'str'>

Python Byte String vs Unicode

Byte strings have a major use in binary data. Encoded data works well with a byte string. Bytes decode into unicode strings while unicode strings are encoded into a byte string. Unicode uses str strings. 

Byte strings change into unicode set by python.

FAQs

What is the difference between a string and a byte string?

String means a set of characters while byte strings refer to the primary group of bytes. Byte string can be converted to a string using encoding.  In the same way, using decoding, one can get byte strings back.

Also, Read >> 4 Best Ways to Convert Hexadecimal to Decimal in Python

Conclusion

In this tutorial, we have learned about the concept of conversion of bytes to string in python. We have discussed all the ways through which we can convert bytes to string. All the ways are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Vicky Singh
Vicky Singh
3 years ago

I am newbie in python, and I think is important for me. So, I rate it for me.

Pratik Kinage
Admin
3 years ago
Reply to  Vicky Singh

Good to know!

A K
A K
2 years ago

The 3rd method works well.

Pratik Kinage
Admin
2 years ago
Reply to  A K

Yes, it’s probably the best method. .docode() is also a simple way of converting!

Joerg
Joerg
2 years ago

Which method has the best performance?

Pratik Kinage
Admin
1 year ago
Reply to  Joerg

str() would be your best option here.