Home »
Python
Best way to convert string to bytes in Python3
Python | Converting string to bytes: Here, we are going to learn about the best way to convert string to bytes in Python3.
Submitted by Sapna Deraje Radhakrishna, on January 19, 2020
To convert a string to bytes, there are more than one way,
Approach 1: use encode() method
test_str = "include_help"
print(type(test_str))
test_bytes = test_str.encode()
print(test_bytes)
print(type(test_bytes))
Output
<class 'str'>
b'include_help'
<class 'bytes'>
In python3, the first parameter to encode() defaults to 'utf-8'. This approach is also supposedly faster because the default argument results in NULL in the C code.
Approach 2: use bytes() constructor
test_str = "include_help"
test_bytes_v2 = bytes(test_str, 'utf-8')
print(type(test_bytes_v2))
print(test_bytes_v2)
Output
<class 'bytes'>
b'include_help'
Using the bytes constructor gives more options than just encoding the string. However, for encoding a string the approach1, is more pythonic than using a constructor, because it is more readable.