Convert string to bytes in Python

The basic definition for bytes is the encoded objects of string that can be stored in disk and can be restored into their original form by decoding them to string.

The common difference between strings and bytes is, strings are a sequence of characters whereas, byte objects are an arrangement of bytes.

If you want to convert a string to bytes, there are some possible ways. In this tutorial, you are going to see two popular ways to convert a string to bytes in Python.

That can be listed as below:

  • Using bytes()

    string = 'I am the king!' # original string
    converted_string_2 = bytes(string,'UTF-8')
    print(converted_string_2)
    print(type(converted_string_2)) # check the type of the object
  • Using encode()
    string = 'I am the king!'
    
    converted_string = string.encode('UTF-8')
    print(converted_string)
    print(type(converted_string))

And the output:

output_tobyteconvo

In the present day, the need for a byte to string conversion is increased. This is because this concept can be used in Machine Learning to store pickle objects in your computer memory.

In our example, we have used the Python bytes() method and encode() method.

Leave a Reply

Your email address will not be published.