In this article, we are going to present how to convert string to bytes in Python 3.
bytearray class to convert string to bytes
Let's start with the
bytearray class that returns a new mutable byte array of given string object. The method can be used to convert
string to bytes easily:
The output of above example:
In this example, we make the use of
bytearray class. Note that converting
bytes always requires
3. Convert string to bytes using
str.encode() function returns an encoded version of the string as a bytes object:
This example produces the following output:
4. string to bytes using
bytes class is an immutable (unchangeable) version of
bytearray class. It also allows us to convert string to bytes. Let's see the following example snippet:
In this article, we illustrated several methods to convert string to bytes in Python 3. Note that this kind of conversions always requires that the encoding of the given string will be given explicitly.