Best way to convert string to bytes in Python 3?

In Python 3, you can convert a string to bytes using the bytes function. The syntax for this function is as follows:

string = 'Hello, world!'
print(bytes(string, encoding='utf-8'))

The string argument is the string that you want to convert to bytes, and the encoding argument is the character encoding that you want to use. The default value for encoding is 'utf-8', which is a widely-used character encoding for Unicode text.

Watch a course Python - The Practical Guide

For example, to convert the string "hello" to bytes using the UTF-8 encoding, you would use the following code:

string = "hello"
b = bytes(string, 'utf-8')

This will output the bytes of the string: b'hello'

Another way of doing this is by using the encode() method of the string itself.

string = "hello"
b = string.encode()

This will give the same result as above.

If you want to convert bytes to string you can use decode function of bytes object or by casting to str()

b = b'hello'
string = b.decode()

string = str(b, 'utf-8')

Both will give the same result 'hello'