Python is a powerful programming language that supports many different types of data including bytes. In most cases, you can directly use byte-type data as strings. But if you are getting an error on your system, then you may need to explicitly convert bytes into string in Python. In this article, we will look at different ways to convert bytes to string in python.
How to Convert Bytes to String in Python
By default, you should be able to directly use byte data as strings. Here is an example on python 2.7.3 where we declare a byte variable and use it as a string.
>>> a=b"abcde" >>> a 'abcde' >>> str(a) 'abcde' >>> type(a) <type 'str'>
If the above code doesn’t work on your system, then you can explicitly convert bytes to string using decode() function.
On Python 2
>>> b"abcde".decode("utf-8") u'abcde'
Alternatively, you can also use unicode() function for the same purpose.
>>> unicode('hello', 'utf-8') u'hello'
On Python 3
You can also use decode() function in Python 3.
>>> encoding = 'utf-8' >>> b'hello'.decode(encoding) u'hello' OR >>> str(b'hello', encoding) u'hello'
In this short article, we have learnt how to convert bytes into strings. You can use these codes in your python script or application, if you are getting errors while trying to use bytes or bytearray data-type as strings.
Also read:
How to Store Output of Cut Command to Shell Variable
How to Use Shell Variables in Awk Script
How to Setup SSH Keys in Linux
How to Create Nested Directory in Python
How to Find Package for File in Ubuntu
Related posts:
How to Redirect Stdout & Stderr to File in Python
How to Intersect Two Dictionaries in Python
How to Drop One or More Columns in Python Pandas
How to Delete All Instances of Character from String in Python
How to Convert string to UTF-8 in Python
How to Extract data from JSON File in Python
How to Merge PDF Files Using Python
What Is __name__ In Python

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.