1. Introduction
In this article, we are going to present how to convert string to bytes in Python 3.
2. Using 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 string
to bytes
always requires encoding
.
3. Convert string to bytes using str.encode()
function
The 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
The 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:
The output:
5. Conclusion
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}