This post will discuss how to convert a string to bytes in Python (and vice versa).

There are two different ways to convert a string to bytes in Python:

1. Using bytes() function

The idea is to use the bytes constructor bytes(string, encoding) to get an array of bytes from a string using the specified encoding.

Download  Run Code

 
To do the reverse, i.e., convert bytes to string, pass the bytes to a string constructor with the encoding used. If no encoding is specified, it uses the current default encoding used by the Unicode implementation.

Download  Run Code

2. Using encode() function

Another option is to use the str.encode function to encode a string using the specified encoding or default encoding utf-8.

Download  Run Code

 
To get a string decoded from the given bytes, you can use the bytes.decode function, which takes the encoding or uses the default encoding utf-8 when no encoding is specified.

Download  Run Code

That’s all about converting a string to bytes in Python.

 
Also See:

Convert bytes to string in Python