How to convert string to bytes in Python 3

May 12, 2020 No comments Python Conversions String Bytes

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:

str = "frontbackend.com"

by = bytearray(str, 'utf-8')

print(type(by))
print(by)

The output of above example:

<class 'bytearray'>
bytearray(b'frontbackend.com')

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:

str = "frontbackend.com"

by = str.encode()

print(type(by))
print(by)

This example produces the following output:

<class 'bytes'>
b'frontbackend.com'

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:

str = "frontbackend.com"

by = bytes(str, 'utf-8')

print(type(by))
print(by)

The output:

<class 'bytes'>
b'frontbackend.com'

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.

{{ message }}

{{ 'Comments are closed.' | trans }}