Convert string to bytes in Python

There are several ways to convert a string value to bytes in Python. Some of them are shown below:

Prefixing b in a String

We can convert a string literal to bytes by prefixing b in it.

Here's an example in which the data type of the first variable is string and the second variable is bytes:

text_string_one = "hello world"
text_string_two = b"hello world"

print(type(text_string_one))
print(type(text_string_two))

The output of the above code is as follows:

<class 'str'>
<class 'bytes'>

The bytes() Method

We can convert a string value to bytes by using the built-in bytes(string, encoding, errors) of Python.

Here's an example of converting a string variable value to bytes using the bytes() method in Python:

text_string = "Hello world"
text_bytes = bytes(text_string, "utf-8")

print(text_bytes)
print(type(text_bytes))

The output of the above code is as follows:

b'Hello world' 
<class 'bytes'>

The encode() String Method

We can also use the encode() method on a string value to convert the string value into bytes. The encode() method optionally takes a parameter to specify the encoding type. If no encoding type is specified, "UTF-8" is used.

Here's an example of using the encode() method to convert string to bytes in Python:

text_string = "Hello world"
text_bytes = text_string.encode("utf-8")

print(text_bytes)
print(type(text_bytes)

The output of the above code is as follows:

b'Hello world'
<class 'bytes'>