Convert String to Bytes in Python

We can encode strings to bytes using Python's built-in methods.

Conversion

We can use several ways to encode string to bytes in Python.

Also we can specify the format e.g. utf-8, shift_jis as argument.

# Using encode() method
"Hello".encode('utf-8')
"Hello".encode('shift_jis')

# Using bytes() method
bytes("Hello", 'utf-8')
bytes("Hello", 'shift_jis')

# Result: b'Hello'

Decode Bytes to String

By the way, we can decode bytes to string with decode method.

b"Hello".decode()
# Hello