Best way to convert string to bytes in Python 3
A byte object is a sequence of bytes. These are machine-readable objects. We can store these directly on the disk. Strings, on the other hand, are human-readable. For the string object to get stored on a disk, it needs to be encoded.
We can convert a string object to a byte object using the below-mentioned ways.
- Using byte()
- Using encode ()
Using byte():
This function implicitly calls the encode() function which converts the string to a byte using the specified encoding. Before doing this conversion, this function internally points to the Cpython Library.
Syntax:
bytes( [source[, encoding[, errors]]] )
- source initializes the array of bytes. It can be a string, an iterable, integer, Nosource(an array of size zero).
- encoding specifies the type of encoding such as utf-8, ascii, etc.
- error specifies the action to be taken when the encoding conversion fails if the source is a string.
All these parameters can be used optionally.
Example:
string_eg = "python by i2tutorials" print("The original string : " + str(string_eg)) string_converted_to_byte = bytes(string_eg, 'utf-8') print("The byte converted string is : " + str(string_converted_to_byte)) print("The type of byte converted string is : " + str(type(string_converted_to_byte)))
output:
Using encode():
This function directly converts a byte object to a string object and it doesn’t link to any external library for its functioning. This method takes in just one parameter which specifies the type of encoding.
Syntax:
string.encode(‘encoding’)
Example:
string_eg = "python by i2tutorials" print("The original string : " + str(string_eg)) string_converted_to_byte = string_eg.encode('utf-8') print("The byte converted string is : " + str(string_converted_to_byte)) print("The type of byte converted string is : " + str(type(string_converted_to_byte)))
output:
Refer to the article to learn how to convert a byte to a string