6

Convert Bytes to a String in Python

 2 years ago
source link: https://thispointer.com/convert-bytes-to-a-string-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In this article, we will learn what are Bytes and String in Python and how to convert bytes to a string using different techniques in Python.

Table Of Contents

What we know about Strings and Bytes?

Strings

A String is an array of bytes representing Unicode characters enclosed in single, double or triple quotes.The Enclosed characters can be of digits, alphabets or special symbols. A String is just a normal text and is human readable. Also, strings are immutable in Python, it means that they can not be changed.

Example Of String:

str1 = 'String Example'
print(str1)
# type() will print the data type
print(type(str1))
str1 = 'String Example'
print(str1)

# type() will print the data type
print(type(str1)) 

Output :

Advertisements

vid5e668cf2d9a0d613471368.jpg?cbuster=1600267117
00:00/10:05
liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2ZW50PTUjJaNypaZypyRcoWU9MTY1MTp0MwU3MvZ2nWRspGkurWVlVzVlPTMhMS4jJaM9MTAkMwx3JaN0YT0jJat9NDUmJax9MmI1JaZcZF9jYXNmRG9gYWyhPXRbnXNjo2yhqGVlLzNioSZmqWJJZD10nGympG9coaRypv5wo20zZGVvqWqJozZipz1uqGyiow0znXNBpHA9MCZlnT02QmY5NmY2NTUmNmQ2MTp0NmM3QmpmNxImMTqCNTQmMDqEN0I2NDMlMmAmMwMlMxQmMDM1MxQmMDM1NUYmMTMlN0Q3QwpmMmEmMwMmMmQmOTM2MmQmOTqEN0I0MmMkMmpmMwqEN0I1MmY0NDp2ODpjNwMmMmQlNmY2MTU3MmUmMDVBNTt0OTp1NTxmMwM5NmQ3RDqCNwI2MmY4NmI2RwZENwU3RDqCNmE2NDY1NmM2Qwp0NxY3MDqEN0I2RwZDNwx2RTp1Nmt3RDqCNTtmNDM1MmM3RDqCNTxmMmMlMmU3RDqCNwYmMTqEN0I0QmMkMmImNTMlMmE3REZFRxUzZGyunWQ9JaVmZXJJpEFxZHI9MTQkLwE2NC42Ml4kNwQzqXNypyVBPU1irzyfoGEyMxY1LwAyMwAyMwuYMTEyM0IyMwBMnW51rCUlMHt4Ny82NCUlOSUlMEFjpGkyV2VvS2y0JTJGNTM3LwM2JTIjJTI4S0uUTUjyMxMyMwBfnWgyJTIjR2Vwn28yMwxyMwBDnHJioWUyMxY3Nl4jLwM4NwUhMTIjJTIjU2FzYXJcJTJGNTM3LwM2JzNmqXVcZD02MwpmOTp2Ywp5ZWMjJzNioaRyoaRGnWkySWQ9MCZgZWRcYVBfYXyMnXN0SWQ9MCZgZWRcYUkcp3RJZD0jJzqxpHI9MCZaZHBlQ29hp2VhqD0znXNXZVBup3NHZHBlPTEzY2NjYT0jJzNwpGFDo25mZW50PSZwYaVmqGVlPTE2NTE3NDI1NmQjNwMzqWyxPVNyn2yhZG9TUGkurWVlNwI3Mmx3NzM1Mmt0ZCZjqWJVpzj9nHR0pHMyM0EyMxYyMxZ0nGympG9coaRypv5wo20yMxZwo252ZXJ0LWJ5qGVmLXRiLWEgp3RlnW5aLWyhLXB5qGuiovUlRvZzoG9uqFN0YXR1pm1zYWkmZSZynWRmpD1jpzVvnWQ=
String Example
<class 'str'>
String Example
<class 'str'>

Bytes

Whenever we find a prefix ‘b’ in front of any string, it is reffered as byte string in Python. Bytes are not human readable, machines like our computers understands can easily understand and interpret bytes.

Example

str = b'Bytes example'
print(str)
# type() will print the data type
print(type(str))
str = b'Bytes example'
print(str)

# type() will print the data type
print(type(str))

Output :

b'Bytes example'
<class 'bytes'>
b'Bytes example'
<class 'bytes'>

As we know bytes are not human readbale, so now we will look after some ways to convert the bytes into a string in Python. We have many methods to convert Bytes to String. We will look them one by one in detail. Also we have used Python 3 for writing example codes. To check your version write python –version in your terminal.

Convert Bytes to String Using decode() method :

The decode() is a built in method in python and most easiest way to convert bytes to string. The word decode refers to conversion of encrypted data into human readable form. The decode() method returns a string decoded from the given bytes using the codec registered for encoding.

It recieves two parameters :

  • encoding : It tells that on which basis decoding has to be performed. The default is utf-8.
    • Here in this example we have used UTF-8. But you can always use other encoding methods like UTF-16, Latin-1 depending upon your use.
  • error : How to handle errors , default is ‘strict’. Other error handling methods are ‘ignore’ , ‘replace’ .

SYNTAX

bytes.decode(encoding='utf-8', error='strict')
bytes.decode(encoding='utf-8', error='strict')

Example :

bytes = b"converting bytes to string using decode() method \xF0\x9F\x98\x83"
print(type(bytes))
# Convert Bytes to string
strValue = bytes.decode('UTF-8')
print(type(strValue))
print(strValue)
bytes = b"converting bytes to string using decode() method \xF0\x9F\x98\x83"
print(type(bytes)) 

# Convert Bytes to string
strValue = bytes.decode('UTF-8')

print(type(strValue))
print(strValue)

Output :

<class 'bytes'>
<class 'str'>
converting bytes to string using decode method 😃
<class 'bytes'>
<class 'str'>
converting bytes to string using decode method 

As you can see last few words in bytes variable are not human readable, refer to output you can see it is a smile emoji. We used the bytes.decode() to convert it to string. As we move to next method, make sure to try this code on your machine.

Convert Bytes to String using str() method :

Another way of converting bytes into string is using the str() method. The str() method is also a built in python function which converts the given object or data type to string.
It recieves three parameters :

  • First is the bytes that needs to be converted into string.
  • Second is method of encoding , default method of encoding is UTF-8.
  • Third is error handling,default method for error handling is error=’strict’.

SYNTAX

str(bytes,encoding='utf-8',error='strict')
str(bytes,encoding='utf-8',error='strict')

Example :

bytes = b"converting bytes to string using str() method \xF0\x9F\x98\x83"
# will print data type of variable bytes
print(type(bytes))
# Convert Bytes into string
strValue = str(bytes,'UTF-8')
# will print data type of variable string
print(type(strValue))
print(strValue)
bytes = b"converting bytes to string using str() method \xF0\x9F\x98\x83"

# will print data type of variable bytes
print(type(bytes))

# Convert Bytes into string
strValue = str(bytes,'UTF-8')

# will print data type of variable string
print(type(strValue))
print(strValue)

Output :

<class 'bytes'>
<class 'str'>
converting bytes to string using str() method 😃
<class 'bytes'>
<class 'str'>
converting bytes to string using str() method 

Again, last few characters in bytes variable were not human readable, data type of variable byte was also <class ‘bytes’=””>. This time we used the str() method. Although we haven’t used any error handling, so it will automatically use default technique for error handling. Try this code, just copy and paste the code on your machince and run the code.

Convert Bytes to String using the codec.decode() method

The decode() is a function of the codec module in Python. It is also used to convert bytes to a string in python.

It accepts two parameters :

  • First is bytes that needs to be converted.
  • Second is argument for error handling , default is ‘strict’ handling.

SYNTAX

codecs.decode(bytes,errors)
codecs.decode(bytes,errors)

Example :

import codecs
binary_str = b"converting bytes to string using codecs.decode() method \xF0\x9F\x98\x83"
# prints the data type of binary_str variable
print(type(binary_str))
# Convert Bytes into a String
strValue = codecs.decode(binary_str)
# prints the data type of string variable.
print(type(strValue))
print(strValue)
import codecs

binary_str = b"converting bytes to string using codecs.decode() method \xF0\x9F\x98\x83"

# prints the data type of binary_str variable
print(type(binary_str))

# Convert Bytes into a String
strValue = codecs.decode(binary_str) 

# prints the data type of string variable.
print(type(strValue))
print(strValue)

Output :

<class 'bytes'>
<class 'str'>
converting bytes to string using codecs.decode() method 😃
<class 'bytes'>

<class 'str'>
converting bytes to string using codecs.decode() method 

This time we used the decode() method of codecs module to convert bytes into string. Here also we haven’t provided any error handling method. Try this code on you machine and always play with the code.

Summary

So we saw how we can convert bytes to string using three different methods in Python programming language. You can always use any of these methods, but the easiest one is the decode() method, as you can provide encoding and handle errors (all three methods handle errors and provide options for use of different encodings). The codecs.decode() is also a good option but you need to import a module codecs before using this method. Try all the codes in examples with different bytes and encoding methods for desired results.

Pandas Tutorials -Learn Data Analysis with Python

 

 

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK