Convert String to Bytes in Python
Last modified: 2023-08-29
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.
- string class has
encode
method to encode strings to bytes. - bytes method converts string to bytes.
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