This concise example-based article shows you how to convert a string to bytes and vice versa in Python.
Converting a string to bytes
To turn a given string into bytes, you can use either the bytes()
function or the str.encode()
method. Both of them take a string as an input and return a bytes object that represents the string in a specified encoding.
Code example:
text = "Welcome to Sling Academy!"
# Convert 'text' to bytes using encode()
bytes_1 = text.encode('utf-8')
# Verify the type of 'bytes_1'
print(type(bytes_1))
# Convert 'text' to bytes using bytes()
bytes_2 = bytes(text, 'utf-8')
# Verify the type of 'bytes_2'
print(type(bytes_2))
Output:
<class 'bytes'>
<class 'bytes'>
The main difference between the two is that the bytes()
function can convert various sources (not just strings) to bytes, while the str.encode()
method specifically operates on strings.
Syntax of the bytes()
function:
bytes(source, encoding, errors)
Where:
source
: The source to be converted. It can be a string, an iterable of integers, or a buffer-like object.encoding
: The encoding to be used for the conversion. Defaults to ‘utf-8’.errors
: Specifies how encoding and decoding errors should be handled. Defaults to ‘strict’.
Syntax of the encode()
method:
your_string.encode(encoding, errors)
Where:
encoding
: The encoding to be used for the conversion. Defaults toutf-8
.errors
: Specifies how encoding and decoding errors should be handled. Defaults tostrict
.
Converting bytes to a string
There are two options for bytes to string conversion.
Using the str() function
You can pass a bytes object to the str()
function to get a string.
Example:
bytes_data = b"Welcome to Sling Academy!"
# bytes to string
string = str(bytes_data, 'utf-8')
# verify the type
print(f"The output is '{string}' and the type is {type(string)}")
Output:
The output is 'Welcome to Sling Academy!' and the type is <class 'str'>
The str()
function can produce a string from an arbitrary object, not limited to a bytes object.
Using the decode() method
You can turn a bytes object into a string by calling the decode()
method on it.
Example:
bytes_data = b"Welcome to Sling Academy!"
# byts to string
string = bytes_data.decode('utf-8')
# verify the type
print(type(string))
Output:
<class 'str'>
Unlike the str()
function, the decode()
method can only convert a bytes object into a string, not an arbitrary object. If you try to use the decode()
method on an object that is not a bytes object, you will get an AttributeError
.