How to Convert Bytes to String in Python

Here are the ways to convert bytes to string in Python:

  1. Using “decode()” method
  2. Using “str()” function
  3. Using “codecs.decode()” method
  4. Using “map()” without using the b prefix
  5. Using pandas to convert bytes to strings

Method 1: Using the decode method

To convert bytes to strings in Python, you can use the “decode()” method. The String decode() method is “used to decode the string using the codec registered for encoding.”

Syntax

decode(encoding, error)

Parameters

  1. encoding: The encoding parameter defines the encoding based on which decoding has to be performed.
  2. error: The error parameter determines how to handle the errors if they occur, e.g., ‘strict‘ raises a Unicode error.

Return Value

It returns the original string from the decoded string.

Example

To convert the bytes object to the original string, you can use the “decode()” method with the exact encoding mechanism. We used utf-8 style encoding, so you must also use the same type of decoding.

str1 = "Hello and welcome to the world of pythön!"
str2 = str1.encode('utf-8')
print(type(str2))
print(str2)

print('After converting from bytes to string')
str3 = str2.decode('utf-8')
print(type(str3))
print(str3)

Output

<class 'bytes'>
b'Hello and welcome to the world of pyth\xc3\xb6n!'
After converting from bytes to string
<class 'str'>
Hello and welcome to the world of pythön!

You can see that the decode() method successfully decodes the bytes object to String.

Method 2: Using the str() function

Python str() function “returns the string version of the object.”

data = b'OpenAI'

print('\nInput:')
print(data)
print(type(data))

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

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

Output

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

Output:
OpenAI
<class 'str'>

Method 3: Using codecs.decode() method

import codecs

data = b'HomerSimpson'

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

# converting
output = codecs.decode(data)

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

Output

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

Output:
HomerSimpson
<class 'str'>

Method 4: Using map() without using the ‘b’ prefix

ascII = [97, 98, 99]
 
string = ''.join(map(chr, ascII))
print(string)

Output

abc

Method 5: Using pandas to convert bytes to strings

import pandas as pd

dic = {'Items': [b'Apple', b'Orange', b'Banana', b'Grapes']}
data = pd.DataFrame(data=dic)

x = data['Items'].str.decode("utf-8")
print(x)

Output

0 Apple
1 Orange
2 Banana
3 Grapes
Name: Items, dtype: object

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.