Home examples • python – Convert bytes to string

python – Convert bytes to string

 - 

Programmers usually think about string as a sequence of letters, which is accurate. But how characters are stored can vary. Some encodings use one byte to store a character, some two and some four.

This example shows what will happen when you change character encoding to a different one.
As an example, we have a two character string ‘PI’, which require 2 bytes of memory to store one character. Look what will happen when you choose different types of encoding.

 

Convert string to bytes

First, set encoding.

Now, try to display these strings and their sizes.

The result is …

 

Convert bytes to string

In order to convert these values back to string, use the following code.

It will give you this result.

 

Convert bytes to string in a file

This example shows how you can use bytes to string conversion in real life example.

First, lets create a text file in windows notepad with the following text:
This computer is worth $900.

When you use the following code:

It will display the binary text.

Decode binary data to a string by using the following code.

Now the string is:

Let’s change the “$” sign to “£” sign.
This computer is worth £900.

When you will try to save the file in notepad, the following message will appear.

If you try to save the file without changing the character encoding, it will result in changing the “£” character to other from the standard ASCII table.
What can we do about it?
Just click OK and change the encoding to Unicode (UTF16), by choosing File >> Save As…. and choosing the proper encoding.

Now, when you open the file it will keep the sign unchanged.

Let’s try to open this file in Python.

Its binary version is absolutelly unreadable.

Add the following code.

And display it as text.
This computer is worth £900.

Author:admin